Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed wildcard substitution

I want to do a substitution based on a wildcard. For example, change all "tenure" to "disposition" only if the word "tenure" comes after an '=' sign. Basically a regex that would match this =.*tenure

The sed command that I have so for this is:

sed 's/=.*tenure/=.*disposition/g' file.txt

However, if I pass this to a file containing:

blah blah blah = change "tenure" to "disposition"

I get

blah blah blah =.*disposition" to "disposition"

instead of:

blah blah blah = change "disposition" to "disposition"

How do I do the substitution such that the wildcard in the regex won't be part of the destination file?

like image 216
Steve Avatar asked Jun 06 '11 22:06

Steve


4 Answers

You need to use a capturing group to capture the text that appears between your equals sign and "tenure".

So

sed 's/=\(.*\)tenure/=\1disposition/g'

Note the use of \1 to reference and use the group you captured.

So in

echo 'blah blah blah = change "tenure" to "disposition"' | sed 's/=\(.*\)tenure/=\1disposition/g'

we get

blah blah blah = change "disposition" to "disposition".

See Regex grouping.

like image 64
MGwynne Avatar answered Sep 17 '22 22:09

MGwynne


sed 's/\(=.*\)tenure/\1disposition/g' file.txt
like image 40
Seth Robertson Avatar answered Sep 21 '22 22:09

Seth Robertson


You need to save matched characters between the = and the tenure to add them to the output:

sed 's/=(.*)tenure/=\1disposition/g' file.txt

Also, you should add the -i option to sed if you want to edit the file inplace (do the modifications to the file itself).

like image 30
Diego Sevilla Avatar answered Sep 17 '22 22:09

Diego Sevilla


You have to use backreference in sed. Use it like this:

sed 's/\(=.*\)tenure/\1disposition/g'
like image 34
anubhava Avatar answered Sep 18 '22 22:09

anubhava