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
...
...
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.
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.
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
<&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
[jaypal:~/Temp] paste -d"\n" file1 file2
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
line4.a
line4.b
This might work for you (GNU sed though):
sed 'R file2' file1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With