How to read 2 files alternatively line by line
In today’s post, we will see several command methods with which we can read 2 files alternatively line by line, which means line #1 from file #1 then line #1 from file 2, then line #2 from file #1 then line #2 from file 2 … and so on. This way of reading will produce a combined file output in which lines are alternated between the files.
Let’s use the two following files as example:
1. Use paste
Using the paste command is the easiest to read 2 files simultaneously:
2. Use awk
Here is the command you can use with awk:
In this command, the variable x is assigned for the 2nd filename “file2″. The ’1′ command prints the lines of file1. getline reads the contents of file2 and prints one line at a time. With this method, the lines of both the files get printed in alternate fashion.
3. Use both paste and awk
You can use both paste and awk to do the task:
Comments are closed.