sed命令:如果存在则如何替换,只需插入? [英] Sed command : how to replace if exists else just insert?

查看:420
本文介绍了sed命令:如果存在则如何替换,只需插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在文件中编辑几行,以便 如果一行以(av或avpgw)开头,则将其替换为新文本, 否则,只需在开头插入新文本即可.

I need to edit several lines in a file such that if a line begins with (av or avpgw) then replace these with new text, else just insert the new text in beginning.

如何使用sed执行此操作?

How can I do this using sed ?

推荐答案

您可以这样做:

sed -e 's/^avpgw/new text/' -e t -e 's/^av/new text/' -e t -e 's/^/new text/' file

这用new text(s///)替换了模式,并跳到了结尾(t).否则,它将尝试下一个模式.另请参见 sed命令摘要.

This replaces the pattern with new text (s///) and jumps to the end (t). Otherwise it tries the next pattern. See also sed commands summary.

您还可以使用;分隔命令:

You can also separate the commands with ;:

sed 's/^avpgw/new text/; t; s/^av/new text/; t; s/^/new text/' file

或将命令放在sed命令文件中:

or put the commands in a sed command file:

s/^avpgw/new text/
t
s/^av/new text/
t
s/^/new text/

并这样称呼:

sed -f commandfile file

如果要忽略大小写,请像s/^av/new text/i一样在替代命令的末尾附加一个i.另一种方法是使用字符集s/^[aA][vV]/new text/进行拼写.但这不是sed特有的,为此,您通常可以搜索正则表达式.

If you want to ignore case, append an i at the end of the substitute command as in s/^av/new text/i. Another way is to spell it out with character sets s/^[aA][vV]/new text/. But that is not sed specific, for this you can search for regular expressions in general.

这篇关于sed命令:如果存在则如何替换,只需插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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