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

时间:2011-01-28 11:39:50

标签: unix

搜索一行后如何获取文件的上一行? 敌人ex:有一个名为fore.dat的文件包含:

: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。 即;输出为:

:Transport:000

:Transport:001

:Transport:004

:Transport:003

2 个答案:

答案 0 :(得分:1)

用哪个命令? grep

grep -B 1 text file.txt

将为您提供匹配的行和之前的行。

答案 1 :(得分:1)

根据Eumiro的回复,grep -B会在比赛前给你一些行:

% grep -B1 '^duplicate$' /usr/share/dict/words 
duplicand
duplicate

如果您只想进行此匹配,则可以执行以下操作:

% grep -B1 '^question$' /usr/share/dict/words | head -n1
questingly

这是一种替代方法,因为您的AIX安装上似乎没有可用的Gnu grep。这使用sedtail

% sed -n '1,/^another$/p' /usr/share/dict/words | tail -n2 | sed -n '1p' 
anoterite