【问题标题】:awk specfic text and print 2 lines aboveawk 特定文本并在上面打印 2 行
【发布时间】:2021-06-05 13:15:25
【问题描述】:

我有一个文件,我需要使用 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”。如何在我的命令中实现这一点以匹配特定于大小写的字符串?

【问题讨论】:

  • 您的grep 命令是否支持-B 选项?这会比 awk 更容易

标签: awk aix tac


【解决方案1】:

对于您显示的示例,您能否尝试以下操作。用 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.
}'

【讨论】:

  • @ChristopherKarsten,它给了我{ unload file name = dupli01608.unl number of rows = 0 } 预期的输出,如果这就是你现在所期望的,请告诉我?谢谢。
  • 抱歉。这是工作。我用猫代替了tac。以为可能是打字错误
  • @ChristopherKarsten,您的欢迎、欢呼和快乐的学习。
【解决方案2】:

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

如果要显示该行和上面的两行,可以这样做:

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

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

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2012-01-19
    • 2015-03-25
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多