使用sed和regex解析无线调查的iwlist命令输出

时间:2014-09-17 22:28:52

标签: regex linux bash parsing sed

我有这个命令,我发现谷歌搜索,但我需要输出

中的mac地址
iwlist ath0 scan | sed -ne 's#^[[:space:]]*\(Quality=\|Encryption key:\|ESSID:\)#\1#p' -e 's#^[[:space:]]*\(Mode:.*\)$#\1\n#p'


Output
ESSID:"Banban"
Quality=18/94  Signal level=-78 dBm  Noise level=-99 dBm
Encryption key:on

有什么办法可以获得mac地址吗?该字段显示为地址:00:00:00:00:00:00:00:00

命令iwlist ath0 scan的原始输出

  ath0      Scan completed :
      Cell 01 - Address: DC:9F:DB:90:AB:24
                ESSID:"Banban"
                Mode:Master
                Frequency:5.57 GHz (Channel 114)
                Quality=18/94  Signal level=-78 dBm  Noise level=-99 dBm
                Encryption key:on
                Bit Rates:6 Mb/s; 9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s
                          36 Mb/s; 48 Mb/s; 54 Mb/s
                Extra:bcn_int=100
                IE: IEEE 802.11i/WPA2 Version 1
                    Group Cipher : CCMP
                    Pairwise Ciphers (1) : CCMP
                    Authentication Suites (1) : PSK
                Extra:wme_ie=dd180050f2020101850003a4000027a4000042435e0062322f00
                Extra:ath_ie=dd0900037f01010000ff7f
                Extra:ubnt_ie=dd0e00156d0000000102b5e102021200
                Extra:htcap_ie=cc011bffff000000000000000000000000000000000000000000
                Extra:mtik_ie=dd26000c42000000011e000000001f660902ff0f41502d4d4f4d454e544f2d320000000000000000
      Cell 02 - Address: DC:9F:DB:08:49:43

3 个答案:

答案 0 :(得分:1)

您可以将grep-E(启用ERE)和--only-matching选项一起使用以获得所需的输出。

iwlist ath0 scan | grep -oE '(ESSID:|Address:|Quality=|Encryption key:).*'
Address: DC:9F:DB:90:AB:24
ESSID:"Banban"
Quality=18/94  Signal level=-78 dBm  Noise level=-99 dBm
Encryption key:on
Address: DC:9F:DB:08:49:43

你甚至可以使用grep的默认RE作为BRE,虽然它可能不那么可读:

iwlist ath0 scan | grep -o '\(ESSID:\|Address:\|Quality=\|Encryption key:\).*'
Address: DC:9F:DB:90:AB:24
ESSID:"Banban"
Quality=18/94  Signal level=-78 dBm  Noise level=-99 dBm
Encryption key:on
Address: DC:9F:DB:08:49:43

答案 1 :(得分:1)

试试这个'awk'表达式:

iwlist ath0 scan | awk '/Quality|ESSID|Encryption key|Address/ { print $0 }'

正如jaypal已经指出的那样,输出中有两个硬件地址。两者都将匹配。输出将包括前导空格(对人类有益,对脚本有害)。如果您不喜欢,请使用

iwlist ath0 scan | awk '/Quality|ESSID|Encryption key|Address/ { gsub(/^[ ]+/,"") ; print $0 }' 

代替。

答案 2 :(得分:1)

使用sed,按如下方式扩展原始命令:

 iwlist ath0 scan | sed \
   -ne 's#^[[:space:]]*\(Quality=\|Encryption key:\|ESSID:\)#\1#p' \
   -e 's#^[[:space:]]*\(Mode:.*\)$#\1\n#p' \
   -ne 's#^.*\(Address: \)#\1#p'

正如Charles Duffy所指出的,当使用GNU sed时(例如在Linux上),语法可以简化如下(使用-r选项启用扩展正则表达式):

 iwlist ath0 scan | sed -r \
   -ne 's#^[[:space:]]*(Quality=|Encryption key:|ESSID:)#\1#p' \
   -e 's#^[[:space:]]*(Mode:.*)$#\1\n#p' \
   -ne 's#^.*(Address: )#\1#p'