[Solved] Renumbering of a column and replace of lines in the file


Following script will change the third column of the input file into the number that you require and the output should be sorted for the third field.

  1. Script : torun.sh

filename=”input.txt”

cat input.txt | while read line
do
key=`echo $line | awk '{print $3}'`
res=`echo $key % 4 | bc`
newvalue=$key
if [ $res -eq "0" ]
then
        newvalue=`expr $key - 2`
fi
if [ $res -eq "1" ]
then
        newvalue=`expr $key + 2`
fi
if [ $res -eq "2" ]
then
        newvalue=`expr $key - 1`
fi
if [ $res -eq "3" ]
then
        newvalue=`expr $key + 1`
fi
echo $line | awk -v v1="$newvalue" '{$3=v1; print}'

done

  1. How to run : ./tunrun.sh | sort -k 3

  2. Please note that awk changes the delimiter of the column to single space. I am not sure whether multiple space or tab is your delimiter. We can easily fix the script to properly display the line with the correct delimiter once you confirm.

solved Renumbering of a column and replace of lines in the file