简体   繁体   中英

sed only replacing last occurrence of match - need to match all

I would like to replace all { } on a certain line with [ ], but unfortunately I am only able to match the last occurrence of the regexp.

I have a config file which has structure as follows:

entry {
    id      123456789
    desc    This is a description of {foo} and was added by {bar}
    trigger 987654321
}

I have the following sed, of which is able to replace the last match 'bar' but not 'foo':

sed s'/\(desc.*\){\(.*\)}/\1\[\2\]/g' < filename

I anchor this search to the line containing 'desc' as I would hate for it to replace the delimiting braces of each 'entry' block.

For the life of me I am unable to figure out how to replace all of the occurrences.

Any help is appreciated - have been learning all day and unable to read any more tutorials for fear that my corneas might crack.

Thanks!

Try the following:

sed '/desc/ s/{\([^}]*\)}/[\1]/g' filename

The search and replace in the above command will only be done for lines that match the regex /desc/ , however I don't think this is actually necessary because sed processes text a line at a time, so even without this you wouldn't be replacing braces on the 'entry' block. This means that you could probably simplify this to the following:

sed 's/{\([^}]*\)}/[\1]/g' filename

Instead of .* inside of the capturing group [^}]* is used which will match everything except closing braces, that way you won't match from the first opening to the last closing.

Also, you can just provide the file name as the final argument to sed instead of using input redirection.

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