打印上一行以及匹配的行

时间:2021-02-23 08:35:06

标签: awk

我想搜索模式,如果匹配,则打印匹配的行和上一行。 我用过代码

awk '/pattern/ {print a}{a=$0}' file

但它只打印匹配行的前一行。如何打印上一行以及匹配的行。

3 个答案:

答案 0 :(得分:4)

在您当前的方法中,当模式匹配时,您首先打印 a,然后将其设置为当前行的值。

这样做的效果是 a 始终具有前一行的值。如果匹配在第一行,您将打印一个空字符串,因为 a 还没有值。


除了记住 a 中的当前行并在下一次迭代中打印之外,您还必须在模式匹配时打印当前行 $0

awk '/pattern/ {
  if (a) print a
  print $0
}
{
  a=$0
}' file

如果 a 的值也可以是空字符串,或者如 Ed Morton 在注释中指出的那样计算为零,您可以从第二行开始打印 a

awk '
/regexp/ {
  if(FNR>1) { print a }
  print $0
}
{
  a=$0
}' file

答案 1 :(得分:4)

你在正确的道路上,你忘记打印当前行了。

awk '
/pattern/{
  if(prev)  { print prev ORS $0 }
  if(FNR==1){ print             }
  next
}
{
  prev=$0
}
' Input_file

我也在这里处理了第一行,如果模式出现在第一行,那么它会简单地打印该行,因为没有前一行。

说明:为以上添加详细说明。

awk '                                 ##Starting awk program from here.
/pattern/{                            ##Checking for specific pattern here.
  if(prev)  { print prev ORS $0 }     ##Checking if prev is NOT NULL then print prev newline current line.
  if(FNR==1){ print             }     ##Checking if its first line then simply print the line.
  next                                ##next will skip all further statements from here.
}
{
  prev=$0                             ##Setting prev to current line here.
}
' Input_file                          ##Mentioning Input_file name here.

答案 2 :(得分:4)

你很接近:

awk '/regexp/{print a $0}{a=$0 ORS}' file

请参阅 How do I find the text that matches a pattern? 并记住在您的问题中包含示例输入/输出。

相关问题