Inserting string in file in nth line after pattern using sed

3.7k Views Asked by At

I want to insert word after nth line after pattern using sed. I tied to modify this command but it inserts only in first line after pattern.

sed -i '/myPattern/a \ LineIWantToinser ' myFile

What command should I use to insert for example in third line after pattern?

3

There are 3 best solutions below

1
On
sed '/pattern/{N;N;N;i \
Line to add after 3 lines with patterne as starting counter
}' YourFile
  • number of N to add line between pattern and inserted line.
  • there is no check for end of file or pattern in the 3 lines. (not specified in PO)
0
On

Easiest way to do it with GNU sed is.. (maybe some direct solution exists!?)

sed -n '/pattern/=' file  

to see line where pattern is (grep also can be used here with -n)

then if linenumber+ numoflines is for example 123

sed '123aSOME INSERTED TEXT AFTER THAT LINE' file  

where little a is append command (after that line, if i is used will be pre pattern line)

ps. I'm eager to see if @neronlevelu (or other sed Lover) will find some better sed solution.

Edit: i've found it, it seems a for append or i for insert must? be on first position on line when using { with ; inside } like

sed '/pattern/{N;N;N;
a  SOME TEXT FOR INSERTING
}' file
0
On

A version with bash and ed:

ed -s myFile <<<$'/myPattern/+3a\n LineIWantToinser \n.\nwq'

ed enables us to use the line addressing /myPattern/+3.