问题描述
我想基于通配符进行替换.例如,仅当单词"tenure"出现在"="符号之后时,才将所有"tenure"更改为"disposition".基本上是与该=.*tenure
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
我为此使用的sed命令是:
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"
我知道
blah blah blah =.*disposition" to "disposition"
代替:
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?
推荐答案
您需要使用捕获组捕获等号和任期"之间出现的文本.
You need to use a capturing group to capture the text that appears between your equals sign and "tenure".
所以
sed 's/=\(.*\)tenure/=\1disposition/g'
请注意使用\1
来引用和使用您捕获的组.
Note the use of \1
to reference and use the group you captured.
所以在
echo 'blah blah blah = change "tenure" to "disposition"' | sed 's/=\(.*\)tenure/=\1disposition/g'
我们得到
blah blah blah = change "disposition" to "disposition".
请参见正则表达式分组.
这篇关于sed通配符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!