gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:55 25 4
gpt4 key购买 nike

我的文字如下所示

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

关于linux - sed,替换第一行的第一次匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38809433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com