如何用sed一次替换多个模式? [英] How to replace multiple patterns at once with sed?

查看:51
本文介绍了如何用sed一次替换多个模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 'abbc' 字符串并且我想替换:

Suppose I have 'abbc' string and I want to replace:

  • ab -> bc
  • bc -> ab

如果我尝试两次替换,结果不是我想要的:

If I try two replaces the result is not what I want:

echo 'abbc' | sed 's/ab/bc/g;s/bc/ab/g'
abab

那么我可以使用什么 sed 命令来替换如下所示的内容?

So what sed command can I use to replace like below?

echo abbc | sed SED_COMMAND
bcab

编辑:实际上文本可能有 2 个以上的模式,我不知道我需要多少个替换.由于有一个回答说 sed 是一个流编辑器,它的替换是贪婪的,我认为我需要为此使用一些脚本语言.

EDIT: Actually the text could have more than 2 patterns and I don't know how many replaces I will need. Since there was a answer saying that sed is a stream editor and its replaces are greedily I think that I will need to use some script language for that.

推荐答案

也许是这样的:

sed 's/ab/~~/g; s/bc/ab/g; s/~~/bc/g'

~ 替换为您知道不会出现在字符串中的字符.

Replace ~ with a character that you know won't be in the string.

这篇关于如何用sed一次替换多个模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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