How to interleave lines from two text files How to interleave lines from two text files unix unix

How to interleave lines from two text files


paste -d '\n' file1 file2


Here's a solution using awk:

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

produces this output:

line 1 from file1line 1 from file2line 2 from file1line 2 from file2...etc

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

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

produces this output:

1: line 1 from file12: line 1 from file21: line 2 from file12: line 2 from file2...etc

Note: this code assumes that file1 is of greater than or equal length to file2.

If file1 contains more lines than file2 and you want to output blank lines for file2 after it finishes, add an 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


@Sujoy's answer points in a useful direction. You can add line numbers, sort, and strip the line numbers:

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

Note (of interest to me) this needs a little more work to get the ordering right if instead of static files you use the output of commands that may run slower or faster than one another. In that case you need to add/sort/remove another tag in addition to the 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-