Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading lines from two files in one while loop

Tags:

bash

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.

  • How can I modify the while loop, such so that it can print the corresponding line from file2.csv?
like image 392
Village Avatar asked Mar 27 '12 07:03

Village


People also ask

How do you read multiple files in UNIX loop?

Fortunately, using a similar for loop, you can insert text into each file with a single command. Execute the following command to insert the file's name, followed by a newline, followed by the text Loops Rule! into each file: for FILE in *; do echo -e "$FILE\nLoops Rule\!" > $FILE; done.

What is the efficient way to see if two files are the same?

Comparison Using cmp GNU cmp compares two files byte by byte and prints the location of the first difference. We can pass the -s flag to find out if the files have the same content. Since the contents of file1 and file2 are different, cmp exited with status 1.

How do I search for two lines in the same file in Linux?

Use comm -12 file1 file2 to get common lines in both files. You may also needs your file to be sorted to comm to work as expected. Or using grep command you need to add -x option to match the whole line as a matching pattern. The F option is telling grep that match pattern as a string not a regex match.


2 Answers

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
like image 54
Mat Avatar answered Sep 27 '22 21:09

Mat


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
like image 27
kev Avatar answered Sep 27 '22 21:09

kev