I'm trying to figure out a working method of extracting data from a file and have it output in a correct format.

Let's say I have a file called data.txt and it looks thusly:

abc 123
def 456

I then want to use a script to parse the data and present it as follows:

first abc second 123
third def fourth 456

So far I've created this:


for i in data.txt; do while read -r a b; do
    echo "First $a second $b"
    echo "third $a fourth $b"

done < data.txt

And the output looks like this:

First abc second 123
third abc fourth 123
First def second 456
third def fourth 456

So instead of reading each line and applying it once and moving onto the next line in data.txt, it keeps applying the same data to the next echo command, and then it moves onto the next line. I know I'm probably overlooking something simple, but it's been a long day. :)

1 Answer 1


You could do two reads in a single loop


while read -r a b && read -r c d; do
  echo "First $a second $b"
  echo "third $c fourth $d"
done < data.txt

Depending on your real application you might also want to look at xargs ex.

xargs -L2 /bin/printf 'First %s second %s\nthird %s fourth %s\n' < data.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .