awk print question

Hello, I have an input file like

123,456,789,321,654,987,IN,OUT,2012,000075,CF34EQ

It has 11 fields separated by comma. I am trying to do this

while read string
do
  var=$(echo $string | awk -F"," '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11}') 
  set -- $var
echo $1
...
...
echo $10
echo $11
done < $tmpdir/appended.dat

Everything goes well, the output is OK until it reach $10 and $11. Then the output is 010 and 011 instead of 000075 and CF34EQ. Can you help, please?

Thanks!

You don't need to use awk here, the special IFS variable controls variable splitting, just use it.

OLDIFS="$IFS"
IFS=","

while read LINE
do
        set -- $LINE # Splits on ,
done < inputfile
IFS="$OLDIFS"

Using pure builtins should make the code literally hundreds of times faster, too.

You might need to use ${10} and ${11}

1 Like

Thanks a lot!

You can also set IFS local to the read command, then you do no need to record and reinstate the old IFS value:

while IFS=, read string
do
  set -- $string
done < inputfile

You need to use curly brackets ( ${10} ) for elements higher then nine other $10, otherwise it get interpreted as $1 with a 0 appended..

1 Like