I have a 2-field csv file with the following values:
subID,Task
A,BLOCK
B,BLOCK
C,Finger
Reading via a read-while loop, if I print the two fields in order...
while IFS=',' read -r -a vars ; do
echo ${vars[0]} ${vars[1]}
done < some.csv
A BLOCK
B BLOCK
C Finger
But if I reverse the print order...
while IFS=',' read -r -a vars ; do
echo ${vars[1]} ${vars[0]}
done < some.csv
A
B
C
In fact, any text before ${vars[1]}
will be ignored:
while IFS=',' read -r -a vars ; do
echo foo bar ${vars[1]} ${vars[0]} foo bar
done < some.csv
A foo bar
B foo bar
C foo bar
Just what is going on? Is BLOCK
some sort of control character in bash?
read
to work, you need to haveIFS
contain the comma. Well, maybe you do. Maybe you do, but you're not showing it. Also the whitespace in the output is off. Which kinda leaves open the door that there might be something else in your script that you're also not showing but which might actually be relevant. – ilkkachu Feb 10 '22 at 22:07cat -A some.csv
(orcat -e
) to see if the file contains anything other than the printable characters, carriage returns or worse. – ilkkachu Feb 10 '22 at 22:09^M
carriage return contained in the second field. Thanks for the clarification! – Zage12 Feb 10 '22 at 22:23A,BLOCK\r
, the second loop there printsBLOCK\r A
, which on my terminal shows up asAOCK
. – ilkkachu Feb 11 '22 at 07:58