sed 通配符替换
我想根据通配符进行替换。例如,仅当“tenure”一词位于“=”符号之后时,才将所有“tenure”更改为“disposition”。基本上是一个与此 =.*tenure
匹配的正则表达式
我对此的 sed 命令是:
sed 's/=.*tenure/=.*disposition/g' file.txt
但是,如果我将其传递到包含以下内容的文件:
blah blah blah = change "tenure" to "disposition"
我得到的
blah blah blah =.*disposition" to "disposition"
不是:
blah blah blah = change "disposition" to "disposition"
我如何做替换使得正则表达式中的通配符不会成为目标文件的一部分?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用捕获组来捕获等号和“tenure”之间出现的文本。
因此
请注意使用
\1
来引用和使用您捕获的组。所以
我们
看到正则表达式分组。
You need to use a capturing group to capture the text that appears between your equals sign and "tenure".
So
Note the use of
\1
to reference and use the group you captured.So in
we get
See Regex grouping.
您需要在
=
和tenure
之间保存匹配的字符,以将它们添加到输出中:此外,您应该添加
-i
选项sed 如果您想就地编辑文件(对文件本身进行修改)。You need to save matched characters between the
=
and thetenure
to add them to the output:Also, you should add the
-i
option to sed if you want to edit the file inplace (do the modifications to the file itself).您必须在 sed 中使用反向引用。像这样使用它:
You have to use backreference in sed. Use it like this: