How to alternate lines of two text files

What is the easiest / fastest way to alternate lines of two (or more) text files? Example:

File 1:

line1.1 line1.2 line1.3 

File 2:

 line2.1 line2.2 line2.3 

Interleaved:

 line1.1 line2.1 line1.2 line2.2 line1.3 line2.3 

I am sure that it is easy to write a small Perl script that opens both of them and performs the task. But I was wondering, is it possible to get away with less code, possibly with a single layer using Unix tools?

+52
linux unix command
Oct 25 2018-10-10T00:
source share
5 answers
 paste -d '\n' file1 file2 
+102
Oct 25 '10 at 4:01
source share

Here is the solution using awk :

 awk '{print; if(getline < "file2") print}' file1 

produces this conclusion:

 line 1 from file1 line 1 from file2 line 2 from file1 line 2 from file2 ...etc 

Using awk can be useful if you want to add additional formatting to the output, for example, if you want to mark each line based on which file it comes from:

 awk '{print "1: "$0; if(getline < "file2") print "2: "$0}' file1 

produces this conclusion:

 1: line 1 from file1 2: line 1 from file2 1: line 2 from file1 2: line 2 from file2 ...etc 

Note: this code assumes that file1 has a length greater than or equal to file2.

If file1 contains more lines than file2, and you want to output empty lines for file2 after it completes, add the else clause to the getline test:

 awk '{print; if(getline < "file2") print; else print ""}' file1 

or

 awk '{print "1: "$0; if(getline < "file2") print "2: "$0; else print"2: "}' file1 
+6
May 9 '15 at 7:07
source share

Here you can make a GUI: paste them into two columns in a spreadsheet, copy all the cells, then use regular expressions to replace the tabs with new lines.

+3
Feb 07 '14 at 4:38
source share

@ Listen to the answer in a helpful direction. You can add line numbers, sort and split line numbers:

 (cat -n file1 ; cat -n file2 ) | sort -n | cut -f2- 

Note (I am interested) it takes a little more work to get the right to order, if instead of static files you use the output of commands that can work slower or faster than each other. In this case, you need to add / sort / delete another tag in addition to line numbers:

 (cat -n <(command1...) | sed 's/^/1\t/' ; cat -n <(command2...) | sed 's/^/2\t/' ; cat -n <(command3) | sed 's/^/3\t/' ) \ | sort -n | cut -f2- | sort -n | cut -f2- 
0
Oct 18 '16 at 16:57
source share
 cat file1 file2 |sort -t. -k 2.1 

It indicates that the delimiter is "." and that we sort by the first character of the second field.

-one
Oct 25 '10 at 4:07
source share



All Articles