How to insert the content of a file into another file (if regexp) in perl/shell
Use the r
command in sed
to append text file:
$ sed -i '/Pointer-file2/r file1' file2$ cat file2line1-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 file2line1-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"
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.