Saturday, November 13, 2021

[SOLVED] How to copy specific lines from file 1 after specific line from file 2?

Issue

I have a file1 and a file2.

I want to copy lines 3,4,5 of file1 into file2, but after line 3.

I tried this, but it didn't work:

sed -i 3r<(sed '3,5!d' file1) file2

Any ideas? (I work with a macOS)

Example file1:

_line_1;
_line_2;
_line_3;
_line_4;
_line_5;

Example file2:

line1;
line2;
line3;
line4;

Example output

line1;
line2;
line3;
_line_3;
_line_4;
_line_5;
line4;

Solution

Using a mix of ed and sed:

printf "%s\n" '3r !sed -n 3,5p file1' w | ed -s file2

Inserts the results of the sed command after line 3 of file2. Said sed prints out lines 3 through 5 of file1. Then it saves the changed file2.



Answered By - Shawn