sed 中不同模式的不同替换

发布于 2024-12-02 20:13:52 字数 474 浏览 0 评论 0原文

我需要替换文件每一行中的两个模式。例如,假设该文件包含以下内容:

pattern1 a1 b1 c1
pattern2 a2 b2 c2
pattern1 a1 b1 c1

基本上,在出现“pattern1”的任何地方,a1 需要替换为 a2,b1 替换为 b2,依此类推。不过,我也想把pattern1改成pattern2。

到目前为止,我有一些接近的东西:

/pattern1/ s/a1 b1 c1/a2 b2 c2/

注意,我想将整个 sed 脚本保留在一个文件中。

更新 所需的输出,这可能不是最好的例子,我会回答任何问题。

pattern2 a2 b2 c2
pattern2 a2 b2 c2
pattern2 a2 b2 c2

I need to replace two patterns in each line of a file. Lets say for example the file contains the following:

pattern1 a1 b1 c1
pattern2 a2 b2 c2
pattern1 a1 b1 c1

Basically, anywhere "pattern1" appears, a1 needs to replaced with a2 and b1 for b2, and so on. However, I also want to change pattern1 into pattern2.

So far I have something that comes kind of close:

/pattern1/ s/a1 b1 c1/a2 b2 c2/

Note, I want to keep the entire sed script in a single file.

UPDATE
Desired output, this may not be the best example, I'll answer any questions.

pattern2 a2 b2 c2
pattern2 a2 b2 c2
pattern2 a2 b2 c2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

原来是傀儡 2024-12-09 20:13:52

有多种方法可以做到这一点。

sed -e '/pattern1/{
        s/a2/a1/
        s/b2/b1/
        s/c2/c1/
        s/pattern1/pattern2/
        }' "$@"

您通常可以通过使用分号代替换行符将其折叠为一行(但 sed 的某些版本对此比其他版本更挑剔)。在这种情况下,-e 并不是绝对必要的。

从问题中尚不完全清楚“a1”是否应该被“a2”替换,反之亦然;这段代码的工作原理是“a1需要替换a2”(意思是“用a1替换a2的出现”),但该示例建议相反的替换。如果需要其他含义,请使用诸如 s/a1/a2/ 之类的行,而不是 s/a2/a1/

There are various ways to do it.

sed -e '/pattern1/{
        s/a2/a1/
        s/b2/b1/
        s/c2/c1/
        s/pattern1/pattern2/
        }' "$@"

You can often collapse that to a single line by using semi-colons in place of newlines (but some versions of sed are fussier about that than others). The -e isn't strictly necessary in this context.

It isn't entirely clear from the question whether 'a1' should be replaced by 'a2' or vice versa; this code works off the wording "a1 needs to be substituted for a2" (meaning "replace occurrences of a2 with a1"), but the example suggests the opposite substitution. If the other meaning is required, then use lines like s/a1/a2/ instead of s/a2/a1/.

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