Append a file in the middle of another file in bash

Viewed 5254

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).

3 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

Could you please try following and let me know if this helps you.

awk 'FNR==3{system("cat file2.txt")} 1' file1.txt

Output will be as follows.

I
am
a
black
dog
named
Cookie

Explanation: Checking here if line number is 3 while reading Input_file named file1.txt, if yes then using system utility of awk which will help us to call shell's commands, then I am printing the file2.txt with use of cat command. Then mentioning 1 will be printing all the lines from file1.txt. Thus we could concatenate lines from file2.txt into file1.txt.

How about

head -2 file1 && cat file2 && tail -1 file1

You can count the number of lines to decide head and tail parameters in file1 using

wc -l file1
Related