sed 通配符替换

发布于 2024-11-13 10:56:54 字数 532 浏览 2 评论 0原文

我想根据通配符进行替换。例如,仅当“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雨巷深深 2024-11-20 10:56:54

您需要使用捕获组来捕获等号和“tenure”之间出现的文本。

因此

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

请注意使用 \1 来引用和使用您捕获的组。

所以

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

我们

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

看到正则表达式分组

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.

你丑哭了我 2024-11-20 10:56:54
sed 's/\(=.*\)tenure/\1disposition/g' file.txt
sed 's/\(=.*\)tenure/\1disposition/g' file.txt
红玫瑰 2024-11-20 10:56:54

您需要在 =tenure 之间保存匹配的字符,以将它们添加到输出中:

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

此外,您应该添加 -i 选项sed 如果您想就地编辑文件(对文件本身进行修改)。

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

孤云独去闲 2024-11-20 10:56:54

您必须在 sed 中使用反向引用。像这样使用它:

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

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

sed 's/\(=.*\)tenure/\1disposition/g'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文