Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a line using sed before a pattern and after a line number?

Tags:

shell

unix

sed

awk

How to insert a line into a file using sed before a pattern and after a line number? And how to use the same in shell script?

This inserts a line before every line with the pattern :

sed '/Sysadmin/i \ Linux Scripting' filename.txt 

And this changes this using line number range :

sed '1,$ s/A/a/' 

So now how to use these both (which I couldn't) to insert a line into a file using sed before a pattern and after a line number or another approach?

like image 905
Nohsib Avatar asked Jun 08 '11 20:06

Nohsib


People also ask

How do you insert a sed line after a pattern?

The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.

How do you insert a first line using sed?

Use sed 's insert ( i ) option which will insert the text in the preceding line.


1 Answers

You can either write a sed script file and use:

sed -f sed.script file1 ... 

Or you can use (multiple) -e 'command' options:

sed -e '/SysAdmin/i\ Linux Scripting' -e '1,$s/A/a/' file1 ... 

If you want to append something after a line, then:

sed -e '234a\ Text to insert after line 234' file1 ... 
like image 78
Jonathan Leffler Avatar answered Sep 29 '22 20:09

Jonathan Leffler