0

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.

rrfeva
  • 77
  • 1
  • 5

2 Answers2

3

read twice:

while read -r first second && read -r third fourth; do 
  echo "$first $second $third $fourth"
done < file
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • It works, thank you. Can you explain why using read twice works? I had tried before using read twice, but on two lines (not &&). It just read from the beginning of the file twice. – rrfeva Apr 17 '19 at 14:43
  • @rrfeva it works because each `read ` call reads one line from input. – oguz ismail Apr 17 '19 at 14:48
0

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.
pjh
  • 6,388
  • 2
  • 16
  • 17