sed wildcard substitution

独自空忆成欢 提交于 2019-12-21 16:49:21

问题


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?


回答1:


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.




回答2:


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



回答3:


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).




回答4:


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

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


来源:https://stackoverflow.com/questions/6258643/sed-wildcard-substitution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!