sed 中不同模式的不同替换
我需要替换文件每一行中的两个模式。例如,假设该文件包含以下内容:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有多种方法可以做到这一点。
您通常可以通过使用分号代替换行符将其折叠为一行(但
sed
的某些版本对此比其他版本更挑剔)。在这种情况下,-e
并不是绝对必要的。从问题中尚不完全清楚“a1”是否应该被“a2”替换,反之亦然;这段代码的工作原理是“a1需要替换a2”(意思是“用a1替换a2的出现”),但该示例建议相反的替换。如果需要其他含义,请使用诸如
s/a1/a2/
之类的行,而不是s/a2/a1/
。There are various ways to do it.
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 ofs/a2/a1/
.