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

问题描述

我有一个文件,我需要使用 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 $6}' 

以上给了我以下内容

dupli00913.unl

输出命令给了我我需要的东西,但必须是“duplicall”表而不是“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”显示后者的前三行。