Antony Johnson
Antony Johnson

Reputation: 41

sed or awk: delete/comment n lines following a pattern before 3 lines

To delete/comment 3 lines befor a pattern (including the line with the pattern):

how can i achive it through sed command

Ref: sed or awk: delete n lines following a pattern

the above ref blog help to achive the this with after a pattern match but i need to know before match


define host{
use                             xxx;
host_name                       pattern;
alias                           yyy;
address                         zzz;
}

the below sed command will comment the '#' after the pattern match for example

sed -e '/pattern/,+3 s/^/#/' file.cfg

define host{
use                             xxx;
#host_name                       pattern;
#alias                           yyy;
#address                         zzz;
#}

like this how can i do this for the before pattern?

can any one help me to resolve this

Upvotes: 2

Views: 239

Answers (3)

potong
potong

Reputation: 58478

This might work for you (GNU sed):

sed ':a;N;s/\n/&/3;Ta;/pattern[^\n]*$/s/^/#/mg;P;D' file

Gather up 4 lines in the pattern space and if the last line contains pattern insert # at the beginning of each line in the pattern space.

To delete those 4 lines, use:

sed ':a;N;s/\n/&/3;Ta;/pattern[^\n]*$/d;P;D' file

To delete the 3 lines before pattern but not the line containing pattern use:

sed ':a;N;s/\n/&/3;Ta;/pattern[^\n]*$/s/.*\n//;P;D'

Upvotes: 1

fred_ glasses
fred_ glasses

Reputation: 21

If tac is allowed : tac|sed -e '/pattern/,+3 s/^/#/'|tac

If tac isn't allowed : sed -e '1!G;h;$!d'|sed -e '/pattern/,+3 s/^/#/'|sed -e '1!G;h;$!d' (source : http://sed.sourceforge.net/sed1line.txt)

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247012

Reverse the file, comment the 3 lines after, then re-reverse the file.

tac file | sed '/pattern/ {s/^/#/; N; N; s/\n/&#/g;}' | tac
#define host{
#use                             xxx;
#host_name                       pattern;
alias                           yyy;
address                         zzz;
}

Although I think awk is a little easier to read:

tac file | awk '/pattern/ {c=3} c-- > 0 {$0 = "#" $0} 1' | tac

Upvotes: 1

Related Questions