Bash – Get lines matching a pattern in one file and put them into a second file matching the same pattern

bashlinuxtext processing

Let's say I have 2 files each containing lines which start with a 'b' character and I only want to merge these lines in the same order they appear in the first file.

First File (1.txt)

b 12 32
b 23 43
b 23 63

Second File (2.txt)

a 1322
c 233
g 23324
s 24352

b
h vd2 3f4g

a 2t42
c 34536
g h3443e
s 24h455

b
h 3434gggdfbv4

a 423gwg
c f24bv
g 34g 45h
s 4zth5

b
h 3456zh543

You can see that in the second file the lines which start with a 'b' character don't contain any more information while in the first file I have lines only starting with a 'b' followed by some integer values.

What I need now is something which gets the integers from the first file and puts them into the second files 'b' lines the same way the appear in the first file. So the second file should in the end look like this:

merged file (3.txt)

a 1322  
c 233  
g 23324  
s 24352  

b 12 32  
h vd2 3f4g  

a 2t42  
c 34536  
g h3443e  
s 24h455  

b 23 43  
h 3434gggdfbv4  

a 423gwg  
c f24bv  
g 34g 45h  
s 4zth5  

b 23 63  
h 3456zh543  

join command seems to be able to do what I want but I can't find a way to tell it to only work on lines matching the leading 'b' character.
I also thought about a loop walking through file 1 to get the line numbers matching the patter '^b' and then use them to replace the lines matching pattern '^b' in file 2 but again I can't find a working solution. Does anyone have an idea to accomplish my task with a one-liner or a short bash script?

Best Answer

With GNU sed:

sed -e '/^b/{R 1.txt' -e 'd}' 2.txt

if you want to edit file 2.txt "in place", add sed's option -i.

Related Question