Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert the content of a file into another file (if regexp) in perl/shell

File1 Contents:

line1-file1      "1" 
line2-file1      "2"
line3-file1      "3" 
line4-file1      "4" 

File2 Contents:

line1-file2     "25"  
line2-file2     "24"  
Pointer-file2   "23"  
line4-file2     "22" 
line5-file2     "21"

After the execution of perl/shell script,

File 2 content should become

line1-file2     "25"  
line2-file2     "24"  
Pointer-file2   "23" 
line1-file1      "1" 
line2-file1      "2"
line3-file1      "3" 
line4-file1      "4"  
line4-file2     "22" 
line5-file2     "21"

i.e Paste the contents of file 1 in file 2 after that "Pointer" containing line.

Thanks

like image 988
user1228191 Avatar asked Dec 17 '22 03:12

user1228191


1 Answers

Use the r command in sed to append text file:

$ sed -i '/Pointer-file2/r file1' file2

$ cat file2
line1-file2     "25"
line2-file2     "24"
Pointer-file2   "23"
line1-file1      "1"
line2-file1      "2"
line3-file1      "3"
line4-file1      "4"
line4-file2     "22"
line5-file2     "21"

Use the r command in ed to insert text file:

$ echo -e '/Pointer/-1r file1\n%w' | ed -s file2

$ cat file2
line1-file2     "25"
line2-file2     "24"
line1-file1      "1"
line2-file1      "2"
line3-file1      "3"
line4-file1      "4"
Pointer-file2   "23"
line4-file2     "22"
line5-file2     "21"
like image 157
kev Avatar answered May 13 '23 14:05

kev