awk 特定文本并在上面打印 2 行

awk specfic text and print 2 lines above

我有一个文件,我需要在使用 awk 的匹配结果上方添加 2 行。我已经将下面的内容放在一起,到目前为止还不错,但是我想使用匹配大小写进行搜索:

#cat data.out
{ unload file name = dupli00913.unl number of rows = 251 }

create table vodac.duplicall2
{ unload file name = dupli01608.unl number of rows = 0 }

create table vodac.duplicall

我用来实现我想要的命令如下:

cat data.out | awk "/create table vodac.duplicall/{for(i=1;i<=x;)print a[i++];print} {for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}"  x=2 | head -1 | awk '{print }' 

上面给出了下面的:

dupli00913.unl

输出命令给了我我需要的,但必须是“duplicall”table而不是“duplicall2”。我怎样才能在我的命令中实现这一点以匹配特定于大小写的字符串?

根据您展示的示例,请您尝试以下操作。在 GNU awk.

中编写和测试
tac Input_file | 
awk '
  /create table vodac\.duplicall$/{
    found=1
    next
  }
  found && ++count==2{
    print
    exit
}'

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

tac Input_file |                        ##Using tac Input_file to print lines in reverse order(from last line to first line).
awk '                                   ##Sending tac command output to awk program here.
  /create table vodac\.duplicall$/{     ##Checking condition if line contains create table vodac\.duplicall here.
    found=1                             ##If above condition is TRUE then set found to 1 here.
    next                                ##next will skip all further statements from here.
  }
  found && ++count==2{                  ##Checking condition if found is SET and count is 2 then do following.
    print                               ##Printing current line here.
    exit                                ##exiting from program from here.
}'

如果你想用“awk”显示上面那两行,我不知道。

如果你想显示上面的线和两行,你可以这样做:

grep -n 2 "text" <filename> | head -n 3

在那一行中,“grep -n 2”显示了该行和周围的两行,“head -n 3”显示了后者的前三行。