sed,替换第一行的第一次匹配

时间:2016-08-06 22:52:53

标签: linux bash awk sed

我的文字如下所示

this This that
it It Its
my My Mine
this This that
it It Its
my My Mine

我想替换第一次匹配的第一行。例如。匹配包含my的行,然后替换该行。我做了

cat txt|sed "0,/my/c\my changed line" txt

打印关闭如下图所示,前两行被修剪。

my changed line
this This that
it It Its
my My Mine

如果我运行此cat txt|sed "s/my/changeline/" txt

输出低于

this This that
it It Its
changeline My Mine
this This that
it It Its
changeline My Mine

如何获得如下结果?

this This that
it It Its
changeline My Mine
this This that
it It Its
my My Mine

2 个答案:

答案 0 :(得分:1)

使用sed

sed '0,/.*my.*/s//my changed line/' file

这是做什么的, 在0,/.*my.*/范围内,它会将匹配的.*my.*替换为"我更改的行"。

相同的稍微容易理解的版本:

sed '0,/my/{/.*my.*/s//my changed line/}' file

使用awk逻辑稍微容易理解:

awk '!/my/ || seen { print } /my/ && !seen { print "my changed line"; seen = 1 }' file

答案 1 :(得分:1)

$ awk '/my/ && !f++{$0="changeline My Mine"} 1' file
this This that
it It Its
changeline My Mine
this This that
it It Its
my My Mine