【问题标题】:sed, replacing first occurrence match of the first linesed,替换第一行的第一次出现匹配
【发布时间】:2016-08-07 07:19:06
【问题描述】:

我的文字如下所示

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

【问题讨论】:

    标签: linux bash awk sed


    【解决方案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
    

    【讨论】:

      【解决方案2】:
      $ 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
      

      【讨论】:

        猜你喜欢
        • 2012-02-27
        • 2020-04-27
        • 1970-01-01
        • 1970-01-01
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多