[英]sed, replacing first occurrence match of the first line
my text looks like below 我的文字如下
this This that
it It Its
my My Mine
this This that
it It Its
my My Mine
I want to replace the first line of the first occurrence match. 我想替换第一个匹配项的第一行。 eg.
例如。 match the line which contains
my
then replace the line. 匹配包含
my
的行,然后替换行。 I did 我做了
cat txt|sed "0,/my/c\my changed line" txt
The print off looks below, the first 2 line are trimmed. 打印内容如下所示,前两行被剪裁。
my changed line
this This that
it It Its
my My Mine
if I run this cat txt|sed "s/my/changeline/" txt
如果我运行
cat txt|sed "s/my/changeline/" txt
The output is below 输出如下
this This that
it It Its
changeline My Mine
this This that
it It Its
changeline My Mine
How can I get the result like below? 如何获得如下所示的结果?
this This that
it It Its
changeline My Mine
this This that
it It Its
my My Mine
Using sed
: 使用
sed
:
sed '0,/.*my.*/s//my changed line/' file
What this does, in the range of 0,/.*my.*/
it will replace the matched .*my.*
with "my changed line". 这样做是在
0,/.*my.*/
范围内,它将匹配的.*my.*
替换为“我的更改的行”。
An equivalent slightly easier to understand version of the same thing: 相同的东西的同等版本稍微容易理解:
sed '0,/my/{/.*my.*/s//my changed line/}' file
Using awk
the logic is slightly easier to understand: 使用
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.