Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a file in the middle of another file in bash

I need to append a file in a specific location of another file. I got the line number so, my file is:

file1.txt:

I
am
Cookie

While the second one is

file2.txt:

a
black
dog
named

So, after the solution, file1.txt should be like

I
am
a
black
dog
named
Cookie

The solution should be compatible with the presence of characters like " and / in both files.

Any tool is ok as long as it's native (I mean, no new software installation).

like image 842
Wyatt Gillette Avatar asked Mar 08 '23 23:03

Wyatt Gillette


1 Answers

Another option apart from what RavinderSingh13 suggested using sed: To add the text of file2.txt into file1.txt after a specific line:

sed -i '2 r file2.txt' file1.txt

Output:

I
am
a
black
dog
named
Cookie

Further to add the file after a matched pattern:

sed -i '/^YourPattern/ r file2.txt' file1.txt
like image 66
Ardit Avatar answered Mar 16 '23 05:03

Ardit