user1228191
user1228191

Reputation: 681

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

Upvotes: 4

Views: 2408

Answers (2)

kev
kev

Reputation: 161664

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"

Upvotes: 8

Julian Fondren
Julian Fondren

Reputation: 5619

I'd use Tie::File. Roughly,

use Tie::File;
tie my @a, 'Tie::File', 'File2' or die;
tie my @b, 'Tie::File', 'File1' or die;
for (0..$#a) {
  if (/^Pointer-file2/) {
    splice @a, $_, 0, @b;
    last
  }
}

It's longer than that use of sed, but it should also be easier to see how you'd alter this for slightly different tasks.

Upvotes: 4

Related Questions