Grim Edge
Grim Edge

Reputation: 27

SED change text between matches without affecting the matches

I have some text

#MATCH1
command 1
command 2
command 3
#MATCH2

sed -i '/MATCH1/,/MATCH2/' s/^/#/' <filename>

Does

##MATCH1
#command 1
#command 2
#command 3
##MATCH2

And what i want is

#MATCH1
#command 1
#command 2
#command 3
#MATCH2

Anyone has any idea how to do this? Without post processing the output

Thank you

Upvotes: 1

Views: 51

Answers (2)

Ed Morton
Ed Morton

Reputation: 203149

sed is for doing s/old/new, that is all. For anything else you should be using awk:

$ awk '/MATCH2/{f=0} f{$0="#" $0} /MATCH1/{f=1} 1' file
#MATCH1
#command 1
#command 2
#command 3
#MATCH2

That will work using any awk in any shell on any UNIX box and is utterly trivial to modify if/when you want to do anything else.

Upvotes: 1

anubhava
anubhava

Reputation: 784898

You may use this sed that make sure we don't have # at line start:

sed '/MATCH1/,/MATCH2/ s/^[^#]/#&/' file

#MATCH1
#command 1
#command 2
#command 3
#MATCH2

Note that this only matches non-empty lines between given keywords. Alternatively you may use this sed:

sed '/MATCH1/,/MATCH2/ { /^#/! s/^/#/; }' file

Upvotes: 1

Related Questions