简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM