使用 grep 或 AWK 在搜索到的字符串后提取一行

ehs*_*adi -2 awk grep

有一个命令给我一个很长的输出。我只想提取其中的一行。该行发生变化,但所需行之前的两行始终相同。如何仅通过搜索前一行来提取这一行:命令输出示例如下:

  foo-bar blahblah
  ===============
    foo bar foo bar foo bar.

  this string is always the same (search string)
  ===============
    the desired line is here

==========
foofoofoo
==========

Run Code Online (Sandbox Code Playgroud)

我已经尝试过了

awk '/this string is always the same/{p=1} NF{out=$2}  END{if(p==1){print out}}'
Run Code Online (Sandbox Code Playgroud)

没有 if 部分但它不起作用

我需要的结果是这样的:

the desired line is here
Run Code Online (Sandbox Code Playgroud)

Ed *_*ton 5

如果没有OP发布他们自己解决问题的尝试,我通常不会发布答案,但由于已经得到了答案getline,其中包括一个使用的答案,这是另一个:

$ awk '/this string is always the same/{a[NR+2]} NR in a' file
    the desired line is here
Run Code Online (Sandbox Code Playgroud)

它将当前行与“这个字符串...”进行匹配,如果找到,a[]则用当前行号加 2 填充数组。然后它测试每个行号,如果它在则a[]打印该行。

请注意,即使您的输入之后没有 2 行,上述内容也将起作用this string is always the same

$ printf 'foo\nthis\n' | awk '/foo/{a[NR+2]} NR in a'
$
Run Code Online (Sandbox Code Playgroud)

或者有 2 条这样的背靠背的线:

$ printf 'foo\nfoo\nthis\nthat\n' | awk '/foo/{a[NR+2]} NR in a'
this
that
Run Code Online (Sandbox Code Playgroud)

请参阅http://awk.freeshell.org/AllAboutGetline了解为什么不用getline于此目的。