首页 > 解决方案 > 通过在 grep 之后组合来替换工作

问题描述

在执行 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'

但它不起作用。

有什么建议吗?

谢谢

标签: awksedgrepcat

解决方案


使用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

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


推荐阅读