搜索特定行后如何输出文件的上一行? [英] How do I output the previous line of a file after searching for a specific line?

查看:51
本文介绍了搜索特定行后如何输出文件的上一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索一行后如何获取文件的上一行?

How do I get the previous line of a file after searching for one line?

示例:有一个名为 fore.dat 的文件,其中包含:

Example: There is a file called fore.dat containing:

:Server:APBS

        :Max Blocking queue:20

:Transport:000

        :Server:APBS

        :Max Transactions:10

        :MaxConnections:1

:Transport:001

        :Server:APBS

        :Max Transactions:10

        :MaxConnections:1

:Transport:005
        :Server:BIT

        :Max Transactions:10

        :Max Connections:1

:Transport:004

        :Server:APBS

        :Max Transactions:44440

        :Max Connections:1

:Transport:002

        :Server:BET

        :Max Transactions:10

        :Max Connections:1

:Transport:003

        :Server:APBS

        :Max Transactions:50

        :Max Connections:1

我想将包含服务器名称的传输编号打印为 APBS.IE;输出为:

I want to print the Transport number containing server name as APBS. i.e; the output as:

:Transport:000

:Transport:001

:Transport:004

:Transport:003

推荐答案

这看起来像是 awk 的工作,它甚至应该适用于没有 gawk 的 AIX代码>...

This looks like a job for awk and it should even work on AIX where you don't have gawk...

% awk -F':' '
/^:Transport:/ {
    transport = $0
}

NF == 3 && $2 == "Server" && $3 == "APBS" {
    printf "%s\n\n", transport
}

' fore.dat


:Transport:000

:Transport:001

:Transport:004

:Transport:003

说明:

  • 调用awk
  • 将:"视为字段分隔符.
  • 对于任何以 ':Transport:' 开头的行,将整行存储为 transport.
  • 对于任何包含三个字段的行,其中第二个是Server",第三个是APBS",打印 transport 的最后存储值,后跟一对换行符.
  • 使用 fore.dat 作为输入文件.
  • Call awk
  • Treat ':' as the field separator.
  • For any lines starting with ':Transport:', store that entire line as transport.
  • For any lines with three fields where the second is "Server" and the third is "APBS", print the last stored value of transport followed by a pair of newlines.
  • use fore.dat as the input file.

有许多不同的方法可以做到这一点.这只是一个.

There are a number of different ways you could do this. This is just one.

这篇关于搜索特定行后如何输出文件的上一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆