bash从文件中提取某些行

时间:2015-08-05 12:55:58

标签: bash

我的文件是这样的:

[some_lines_unimportant]
#Field List (hex, dec, bin, char)
00 00 1e 14 0 0 30 20 999909999 000090000 0001-1110
(...)
00 00 3e 01 0 0 62 01 888888888 000088000 0100-1000
[some_lines_unimportant]

我希望能够提取3行下的f.e #Field list ...行。我怎么能用bash做到这一点。

编辑:

这是文件:

# ------------------------------------------------------------------------------------
# ======= Pkt to be transmitted (hex) ================================================
01 00 fe 03 4d 00 00 00 00 02 fe 00 aa 00 00 00 00 00 00 00 04 b8 EOP
# Initiating transfer ...
# ======= Received pkt (hex) =========================================================
02 fe 03 0d 00 fe 00 aa 00 00 00 04 84 00 01 00 10 cc EOP
# ========= Reply pkt fields (hex) ===================================================
  Reply SpW Addr:
02 
# Initiator Log Addr (1 byte), Proto ID (1 byte), Instr (1  byte), Status (1 byte):
fe 03 0d 00 
# Target Log Addr (1 byte), Trans ID (2 bytes MS LS), Reserved (1 byte):
fe 00 aa 00 
# Data Length (3 bytes MS to LS), Header CRC (1 byte):
00 00 04 84 
# Field List (hex, dec, bin, char, [dec line count]):
00 01 00 10    0   1   0  16 0000-0000 0000-0001 0000-0000 0001-0000 . . . . [      1]

# Data CRC (1 byte):
cc
# End of Pkt character:
EOP
# ------------------------------------------------------------------------------------
# @@@@@@@@@ Transaction time: 0.225 ms
######### End of online test #########################################################

2 个答案:

答案 0 :(得分:2)

像这样使用grep,其中-A指定 AFTER 匹配的行数:

grep -A 3 "^#Field List" file

#Field List (hex, dec, bin, char)
00 00 1e 14 0 0 30 20 999909999 000090000 0001-1110
(...)
00 00 3e 01 0 0 62 01 888888888 000088000 0100-1000

或者,如果您不想要第一行匹配

grep -A 3 "^#Field List" file | sed 1d

00 00 1e 14 0 0 30 20 999909999 000090000 0001-1110
(...)
00 00 3e 01 0 0 62 01 888888888 000088000 0100-1000

回旋(或帽子,^)匹配行的开头,即单词#Field必须位于行的最开头才能匹配。

答案 1 :(得分:1)

grep--after-context / -A参数一起使用:

grep -A3 '#Field List'