我需要在一个文件中编辑几行,如果一行以(av或avpgw)开始,那么用新的文本replace它们,否则就在开头插入新的文本。
我如何使用sed来做到这一点?
你可以这样做:
sed -e 's/^avpgw/new text/' -et -e 's/^av/new text/' -et -e 's/^/new text/' file
这用new text
替换模式(s ///)并跳转到结尾(t)。 否则,它会尝试下一个模式。 另请参阅sed命令汇总 。
你也可以把命令分开;
:
sed 's/^avpgw/new text/; t; s/^av/new text/; t; s/^/new text/' file
或者把这些命令放在一个sed命令文件中:
s/^avpgw/new text/ t s/^av/new text/ t s/^/new text/
并用这种方式来调用它:
sed -f commandfile file
如果你想忽略大小写,那么在替换命令的末尾追加一个i,如s/^av/new text/i
。 另一种方法是用字符集s/^[aA][vV]/new text/
来拼出来。 但是这不是sed
特定的,因此您可以搜索正则表达式。
这可能适用于你(GNU sed):
sed -r 's/^av(pgw)?.*/replacement/;t;s/^/replacement /' file