用 sed 替换两个已知字符串之间的未知字符串 [英] replace a unknown string between two known strings with sed

查看:17
本文介绍了用 sed 替换两个已知字符串之间的未知字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下内容的文件:

I have a file with the following contents:

WORD1 WORD2 WORD3

如何使用sed将WORD1和WORD3之间的字符串替换为foo,使文件内容变为如下所示?:

How can I use sed to replace the string between WORD1 and WORD3 with foo, such that the contents of the file are changed to the following?:

WORD1 foo WORD3

我尝试了以下操作,但显然我遗漏了一些东西,因为这不会产生预期的结果:

I tried the following, but obviously I'm missing something because that does not produce the desired results:

sed -i '' 's/WORD1.*WORD3/foo/g' file.txt

推荐答案

sed -i 's/WORD1.*WORD3/WORD1 foo WORD3/g' file.txt

sed -i 's/(WORD1).*(WORD3)/1 foo 2/g' file.txt

您可能需要转义圆括号,这取决于您的 sed 变体.

You might need to escape round brackets, depends on your sed variant.

这篇关于用 sed 替换两个已知字符串之间的未知字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆