Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read 1 line from 2 files sequentially?

Tags:

bash

unix

How do I read from 2 files 1 line at a time? Say if I have file1 and file2 with following content:

file1:

line1.a    
line2.a   
line3.a   

file2:

line1.b   
line2.b   
line3.b   

How do I get output like this -

line1.a   
line1.b   
line2.a   
line2.b   
line3.a   
line3.b   
...
...
like image 938
New User Avatar asked Dec 18 '11 07:12

New User


People also ask

How do I find the common line between two files?

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.

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

Probably the easiest way to compare two files is to use the diff command. The output will show you the differences between the two files. The < and > signs indicate whether the extra lines are in the first (<) or second (>) file provided as arguments.


2 Answers

You can do it either via a pure bash way or by using a tool called paste:

Your files:

[jaypal:~/Temp] cat file1
line1.a
line2.a
line3.a
line4.a

[jaypal:~/Temp] cat file2
line1.b
line2.b
line3.b
line4.b

Pure Bash Solution using file descriptors:

<&3 tells bash to read a file at descriptor 3. You would be aware that 0, 1 and 2 descriptors are used by Stdin, Stdout and Stderr. So we should avoid using those. Also, descriptors after 9 are used by bash internally so you can use any one from 3 to 9.

[jaypal:~/Temp] while read -r a && read -r b <&3; do
> echo -e "$a\n$b";
> done < file1 3<file2
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
line4.a
line4.b

Paste Utility:

[jaypal:~/Temp] paste -d"\n" file1 file2
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
line4.a
line4.b
like image 200
jaypal singh Avatar answered Oct 20 '22 08:10

jaypal singh


This might work for you (GNU sed though):

sed 'R file2' file1
like image 41
potong Avatar answered Oct 20 '22 09:10

potong