首页 > 解决方案 > Bash:替换特定列中的模式,但仅在两个模式之间的行中

问题描述

我有这种结构的文件:

abc
def
ghi
...
x x y x x
x x z x x
x x y x x
...
JKL
x x y x x
x x z x x
x x y x x
...
...
*empty line*
mno
pqr
...
...

我想将整个文件复制到一个新文件中,但要进行一些更改。拳头,我只想影响模式 JKL 和下一个空行之间的行。最重要的是,我需要将模式 y 的每次出现都替换为新模式 NEW,但前提是它出现在第三列中。

我尝试使用 sed,但我陷入了如何选择列:

sed -ne '/JKL/,/^$/s/y/NEW/'

当然,这将所有列中的 y 替换为 NEW。

我也尝试查找 awk,但我只能找到我所拥有的两个独立需求的示例,并且无法将它们放在一起。我怎么能做到?

标签: bashtextawksed

解决方案


Third column is something that follows the beginning of a line, a sequence of non-spaces, a spaces, another sequence of non-spaces, and finally a space:

sed '/^JKL$/,/^$/s/^\([^ ][^ ]* [^ ][^ ]*\) y /\1 NEW /'

or, if your sed supports -r or -E:

sed -E '/^JKL$/,/^$/s/^([^ ]+ [^ ]+) y /\1 NEW /' 

推荐阅读