0

I have seen many answers to looping through an array in bash so that you not only get the index, but also the variable at that index. For example

for i in "${!foo[@]}"; do 
  printf "%s\t%s\n" "$i" "${foo[$i]}"
done

However, for my variable foo, this is defined as:

foo=$(< varlist.txt)

Where varlist.txt is a simple 10 row textfile consisting of a 4-letter code on each line. When I try the above method, the output is not matching up. What am I missing here?

For example:

vi varlist.txt

 QOP1
 QOP2
 LMA1
 LMA2
 NKO1
 NKO2
 POZ1
 POZ2
 CCS1
 CCS2

vi file_to_test.txt

 #text
 #more header text
 POZ1
 CCS2

The output should be:

 7 POZ1
 10 CCS2

As these are the 7th and 10th index from the varlist file.

WX_M
  • 458
  • 4
  • 20
  • 4
    Your variable is not an array, it's a single string that happens to contain newlines. If you have bash version 4 or later, try defining it with `readarray -t foo < varlist.txt` instead. – Gordon Davisson Jun 03 '19 at 20:47
  • 1
    ...or, in bash 3: `foo=(); while IFS= read -r line; do foo+=( "$line" ); done – Charles Duffy Jun 03 '19 at 20:50

0 Answers0