Village
Village

Reputation: 24383

Reading lines from two files in one while loop

I have a file, file1.csv containing:

This
is
some
text.

I am using while read line to cycle through each line, e.g.:

while read line; do
    echo $line
done < file1.csv

I have another file, with an identical number of lines, called file2.csv:

A
B
C
D

The data each line corresponds to data in the first file of the same line number.

Upvotes: 9

Views: 10154

Answers (3)

kev
kev

Reputation: 161674

You can use the paste command:

$ paste -d, file{1,2}.csv | while IFS=, read x y; do echo "$x:$y"; done
This:A
is:B
some:C
text.:D

Upvotes: 9

Mat
Mat

Reputation: 206699

You could try with the paste utility:

$ cat one
this
is
some
text
$ cat two
1
2
3
4
$ while read a b ; do echo $a -- $b ; done < <(paste one two)
this -- 1
is -- 2
some -- 3
text -- 4

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Use another FD.

while read line; do
  if ! read -u 3 line2
  then
    break
  fi
  echo "$line***$line2"
done < file1.csv 3< file2.csv

Upvotes: 15

Related Questions