Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interweave two files bash script

Tags:

bash

sed

awk

I am trying to interweave two files that contain one sentence per line. I double spaced (sed G) the first file and I would like to incorporate the content of the second file into those empty lines.

How can I interweave both files so that the 1st line of file B goes below the 1st line in file A, the 2nd line of file B below the 2nd line of file A, until it reaches the end ?

Example: [line number|sentence number|sentence]

1  1 fileA
2   
3  2 fileA
4  
5  3 fileA
6  
7  4 fileA

Expected result:

1  1 fileA
2  1 FILEB
3  2 fileA
4  2 FILEB
5  3 fileA
6  3 FILEB
7  4 fileA

This is for a bash script: can it be done with sed or awk?

like image 560
octosquidopus Avatar asked Mar 19 '26 13:03

octosquidopus


2 Answers

This might work for you (GNU sed):

sed 'R fileB' fileA

You don't need to double space the file first.

If you want to replace the empty lines though:

sed -e '/./!{R fileB' -e ';d}' fileA
like image 176
potong Avatar answered Mar 21 '26 02:03

potong


If you have the original unspaced files, you can use paste plus (GNU) sed. I'm assuming there are no ^A (Control-A) characters in your sentences:

paste -d'^A' fileA fileB | sed 's/^A/\n/'

The paste command concatenates lines from the two files, and then the sed replaces the marker, ^A, with a newline. This works well with GNU sed; not so well with BSD sed. You can also use awk:

paste -d'^A' fileA fileB | awk '{sub(/^A/, "\n"); print}'

Remember to type Control-A where the ^A appears in the script.

You could also do it easily with Perl, which would only need a single process instead of two as here.


It also occurs to me that you could convert the control characters with tr, which is arguably simpler:

paste -d'^A' fileA fileB | tr '\001' '\012'  # octal escapes for ^A and NL
like image 33
Jonathan Leffler Avatar answered Mar 21 '26 03:03

Jonathan Leffler