Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

sed

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!

like image 530
halfpasthope Avatar asked Oct 07 '22 12:10

halfpasthope


1 Answers

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.

like image 162
Andrew Clark Avatar answered Oct 10 '22 02:10

Andrew Clark