在文件中的搜索模式下方替换第n行 [英] Replace nth line below the searched pattern in a file

查看:34
本文介绍了在文件中的搜索模式下方替换第n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在文件中的搜索模式(例如X)之后替换第4行(其中包含模式Y).请注意,模式Y也用于其他地方.所以我不能直接替换它.另请注意,在第四行上只有一个单词Y.有没有可能可以轻松完成的脚本命令?可能有用",但不确定如何正确使用它.

I needed to replace 4th line (which contain pattern Y) after a search pattern (say X) in a file. Please note pattern Y is used elsewhere too. So I can't replace it directly. Also note on the 4th line there is only one word Y. Is there any scripting command possible that can do with ease? May be "awk" useful but not sure how to use it exactly.

ex:在文件中搜索X的模式.在文件中,我们说

ex: Pattern to search X in a file. In file we have say

X,
C,
D,
Y,
A,

现在我需要替换第4行的Y,以表示 B .

Now I needed to replace Y which is on 4th line to say B,.

推荐答案

行数少:

sed '/X/ { n; n; n; s/Y/B/; }' filename

这很简单:

/X/ {      # If the current line matches /X/
  n        # fetch the next line (printing the current one unchanged)
  n        # and the next line
  n        # and the next line
  s/Y/B/   # and in that line, replace Y with B.
}

由于对于大量用户来说这变得有些笨拙,因此您可能需要考虑在这种情况下使用awk:

Since this becomes somewhat unwieldy for large numbers, you may want to consider using awk for such cases:

awk 'NR == marker { sub(/Y/, "B") } /X/ { marker = NR + 3 } 1' filename

也就是说:

NR == marker { sub(/Y/, "B") }  # if the current line is marked, substitute
/X/ { marker = NR + 3 }         # if the current line matches /X/, mark the one
                                # that comes three lines later for substitution
1                               # print

这篇关于在文件中的搜索模式下方替换第n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆