【问题标题】:Replace work in line by combining after grep通过在 grep 之后组合来替换工作
【发布时间】:2021-08-26 04:27:37
【问题描述】:

我需要在执行 grep 并获得结果的最后一行后替换一个单词。

这是我的示例文件:

aaa ts1 ts2
bbb ts3 ts4
aaa ts5 ts6
aaa ts7 NONE

我需要的是选择所有包含'aaa'的行,获取结果中的最后一行并替换NONE。

我试过了

cat <file> | grep "aaa" | tail -n 1 | sed -i 's/NONE/ts8/g'

但它不起作用。

有什么建议吗?

谢谢

【问题讨论】:

    标签: awk sed grep cat


    【解决方案1】:

    使用tac + awk 解决方案请尝试以下操作。

    tac Input_file | awk '/aaa/ && ++count==1{sub(/NONE/,"ts8")} 1' | tac
    

    一旦您对上述命令感到满意,请尝试以下操作,将就地保存到 Input_file。

    tac Input_file | awk '/aaa/ && ++count==1{sub(/NONE/,"ts8")} 1' | tac > temp && mv temp Input_file
    

    解释: 首先由tac 以相反的顺序打印Input_file,然后将其标准输出发送到awk 作为输入,首先将NONE 替换为ts8行(实际上是包含aaa 的最后一行)。只需打印所有其他行,再次将输出发送到tac 以使其按照实际顺序(如 Input_file 的顺序)。

    【讨论】:

      【解决方案2】:

      为了在单个命令中执行此操作,这应该适用于 awk 的任何版本:

      awk 'FNR==NR {if ($1=="aaa") n=FNR; next} FNR == n {$3="TS7"} 1' file{,}
      
      aaa ts1 ts2
      bbb ts3 ts4
      aaa ts5 ts6
      aaa ts7 TS7
      

      要将输出保存在同一文件中,请使用:

      awk 'FNR==NR {if ($1=="aaa") n=FNR; next}
      FNR == n {$3="TS7"} 1' file{,} > file.out && mv file.out file
      

      或者使用gnu sed,你可以使用:

      sed -i -Ez 's/(.*\naaa[[:blank:]]+[^[:blank:]]+[[:blank:]]+)NONE/\1ts8/' file
      
      cat file
      
      aaa ts1 ts2
      bbb ts3 ts4
      aaa ts5 ts6
      aaa ts7 ts8
      

      【讨论】:

        【解决方案3】:

        如果你想得到最后一行匹配 aaa 的开头,你可以遍历所有行,在 END 块中,打印最后一个匹配项并使用 awk 将 NONE 替换为 ts8

        awk '$1=="aaa"{last=$0}END{sub(/NONE/,"ts8",last);print last}' file
        

        部分:

        $1=="aaa" {               # If the first field is aaa
          last=$0                 # Set variable last to the whole line (overwrite on each match)
        }
        END {                     # Run once at the end                
          sub(/NONE/,"ts8",last)  # Replace NONE with ts8 in the last variable
          print last                 
        }
        ' file
        

        输出

        aaa ts7 ts8
        

        【讨论】:

          猜你喜欢
          • 2016-01-29
          • 1970-01-01
          • 2018-06-27
          • 1970-01-01
          • 2016-05-22
          • 2023-03-03
          • 1970-01-01
          • 1970-01-01
          • 2019-07-31
          相关资源
          最近更新 更多