替换文件中搜索模式下方的第 n 行

amr*_*a47 3 regex awk grep sed

我需要在文件中的搜索模式(比如 X)之后替换第 4 行(其中包含模式 Y)。请注意模式 Y 也用于其他地方。所以我不能直接替换它。另请注意,第 4 行只有一个字 Y。是否有任何脚本命令可以轻松完成?可能“awk”很有用,但不确定如何准确使用它。

例如:在文件中搜索 X 的模式。在文件中我们说

X,
C,
D,
Y,
A,
Run Code Online (Sandbox Code Playgroud)

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

Win*_*ute 8

对于低行数:

sed '/X/ { n; n; n; s/Y/B/; }' filename
Run Code Online (Sandbox Code Playgroud)

这是相当简单的:

/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.
}
Run Code Online (Sandbox Code Playgroud)

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

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

那是:

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
Run Code Online (Sandbox Code Playgroud)