[ACCEPTED]-How to interleave lines from two text files-command

Accepted answer
Score: 172
paste -d '\n' file1 file2


Score: 10

Here's a solution using awk:

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

produces this output:

line 1 from file1
line 1 from file2
line 2 from file1
line 2 from file2

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

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

produces this output:

1: line 1 from file1
2: line 1 from file2
1: line 2 from file1
2: line 2 from file2

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

If file1 contains 3 more lines than file2 and you want to output 2 blank lines for file2 after it finishes, add 1 an else clause to the getline test:

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


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

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

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

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

With GNU sed:

sed 'R file2' file1




Score: 1

Here's a GUI way to do it: Paste them into 3 two columns in a spreadsheet, copy all cells 2 out, then use regular expressions to replace 1 tabs with newlines.

More Related questions