rrfeva
rrfeva

Reputation: 87

How to read in variables from multi-line file?

I am trying to read from a file that is multiple lines with multiple variables per line. There are four variables: item, price, max_qty, and min_qty. The file looks like this:

item price
min_qty max_qty

I have tried:

while IFS=' ' read -r first second third fourth; do
    echo "$first $second $third $fourth
done

This does not work. I want the output to be:

item price min_qty max_qty

I have also thought about somehow replacing the new lines with spaces and then reading from that line. I don't want to actually change the file though.

Upvotes: 0

Views: 857

Answers (2)

pjh
pjh

Reputation: 8084

If it is true that "the file looks like this" (two lines, two values per line, not a larger file with many pairs of lines like that), then you can do it with a single read by using the -d option to set the line delimiter to empty:

read -r -d '' first second third fourth <file
echo "$first $second $third $fourth"
  • The code prints 'item price min_qty max_qty' with the example file.
  • If you have errexit or the ERR trap set, the program will exit immediately, and silently, immediately after the read is executed. See Bash ignoring error for a particular command for ways of avoiding that.
  • The code will work with the default value of IFS (space+tab+newline). If IFS could be set to something different elsewhere in the program, set it explicitly with IFS=$' \t\n' read -r -d '' ....
  • The code will continue to work if you change the file format (all values on one line, one value per line, ...), assuming that it still contains only four values.
  • The code won't work if the file actually contains many line pairs. In that case the "read twice" solution by oguz ismail is good.

Upvotes: 0

oguz ismail
oguz ismail

Reputation: 50750

read twice:

while read -r first second && read -r third fourth; do 
  echo "$first $second $third $fourth"
done < file

Upvotes: 3

Related Questions