Search code examples
linuxbashawkhead

error when using head command inside while loop


Friends,

I am trying to write a script which would take two fields(separated by '.') from a file and interchange them and insert them into another file. The program would do for n number of records. Below given the script

#!/bin/ksh
k=`wc -l file1|cut -d' ' -f1`
i=1
while [ $i -le $k ]
do
    var1=`awk 'BEGIN {FS = "."};{print $2}' file1|head -$i|tail -1`
    var2=`awk 'BEGIN {FS = "."};{print $1}' file1|head -$i|tail -1`
    c="$var1.$var2"
    echo $c >> results.txt
    i=$i+1
done

I am getting the below error in head command. Could you help me here.

head: unrecognized option -+' Tryhead --help' for more information.


Solution

  • The reason is that the line i=$i+1 transforms i into 1+1, then into 1+1+1 and so on.

    Why not just use:

    awk 'BEGIN {FS="."};{print $2"."$1}' <file1 >results.txt