How to insert text using a second file in Linux

How can i insert text at a particular line number or before/after a search pattern? The text i want to insert is of 8-10 lines including new line characters. I have stored this text in a separate file.

I know i can use

sed '{/pattern/|/regexp/|n}{i|a|c}<text to be inserted>' file

But i want <text to be inserted> in a separate file because there are many special characters which i need to escape and that is very hectic if i have large block of text.

I am using Redhat Linux 6.2.

Any better way to do it..?

n=5
insertfile=/path/to/file

{
  head -n "$n"
  cat "$insertfile" -
} < "$file"
1 Like

Try:

sed '3r file2' file1
sed '3r file2' file1

This command is replacing the text.

But i want the text to be inserted.

This command should insert file2 after line 3 of file1. Is that not what you are getting? What is your OS and version?

Hey thanks. My mistake. i was referring to some other file. It worked.
:slight_smile:

Would you mind just trying one more problem i am facing.
http://www.unix.com/shell-programming-scripting/190177-problem-while-replacing-text-between-two-tags.html\#post302656309

Thanks for this though.

Hello Scrutinizer,

I have almost same requirement as of this post. Just one change, I want to insert these lines before a pattern of file1.
Can you pl. tell me how can I do it?

There is only a command ( r ) to append a file, there isn't one to insert it.. I quickly thought of this:

sed 'x;${p;g;};3r file2' file

But it creates an empty line on top...