[英]sed, replacing first occurrence match of the first line
我的文字如下
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
使用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
$ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.