0

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?

Zage12
  • 13
  • For one, for that read to work, you need to have IFS 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:07
  • 1
    Anyway, use something like cat -A some.csv (or cat -e) to see if the file contains anything other than the printable characters, carriage returns or worse. – ilkkachu Feb 10 '22 at 22:09
  • Apologies for the lack of IFS, added with last edit. – Zage12 Feb 10 '22 at 22:21
  • ...there was a ^M carriage return contained in the second field. Thanks for the clarification! – Zage12 Feb 10 '22 at 22:23
  • @Zage12, I wonder if you have a weird terminal, or something. Usually CRs just move the cursor back without clearing the line, so the text that comes after might only partially overwrite the text before. E.g. for the input line A,BLOCK\r, the second loop there prints BLOCK\r A, which on my terminal shows up as AOCK. – ilkkachu Feb 11 '22 at 07:58

0 Answers0