Khalid
Khalid

Reputation: 21

Sed, insert a line after a pattern match and ignore any commented line strating with #

I would like to insert a line after a pattern match and ignore any commented line ( starting with '#' ) in Bash shell using sed.

Here is an example: inserting a new line after pattern:

Input file:

foo
Art 
street 
#pattern
foo
pattern
color

Output:

foo
Art 
street 
#pattern
foo
pattern
NEW LINE HERE
color

Upvotes: 1

Views: 1022

Answers (3)

SLePort
SLePort

Reputation: 15461

Another approach with sed:

sed 's/^pattern.*/&\nNEW LINE HERE/' file

Replace line starting with pattern with matching line(&) followed by new line(\n) and desired string.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133428

try following too once.

awk '/pattern/ && !/#/{print $0 ORS "NEW LINE HERE";next} 1'   Input_file

Upvotes: 0

MauricioRobayo
MauricioRobayo

Reputation: 2356

With sed:

$ cat file
foo
Art
street
#pattern
foo
pattern
color

$ sed '/^[^#]*pattern/ a NEW LINE HERE' file
foo
Art
street
#pattern
foo
pattern
NEW LINE HERE
color

Upvotes: 1

Related Questions