2014-12-10 100 views
0

我有以下输出的linux命令brctl show。我想提取所有关联的接口(如接口列中给出的)并将其存储在某个数组中。有人可以提出一种方法来实现这一目标吗?如何使用shell脚本提取列下的行

[email protected]:~# brctl show 
bridge name bridge id   STP enabled interfaces 
br-lan  7fff.00c0ca7e0288 no   eth0 
              wlan1_1 
              wlan1_1.sta1 

我缺少确切的格式,出于某种原因。但brctl show的输出看起来与上面几乎相同,只有少数几个间距。

因此,如果可能,我想将eth0,wlan1_1,w; an1_1.sta1存储在某个数组中。

感谢

回答

1

您可以使用cuttail。您可能需要调整数量:

brctl show | tail -n +2 | cut -c 36- 

如果tab字符被转换到你的输出空间,你将需要:

brctl show | tail -n +2 | cut -c 46- 

bash脚本解决方案

注意:我测试了您的数据的数据文件,但它也应该与brctl show输出一起使用:

#!/bin/bash 

declare -i cnt=0 
declare -a ifaces 

while read -r line || [ -n "$line" ]; do 
    [ $cnt -eq 0 ] && { ((cnt++)); continue; } 
    ifaces+=("${line//* /}") 
done <<<$(brctl show) 

printf "%s\n" ${ifaces[@]} 

done <"$1"测试作为替代品:

$ bash brctl.sh dat/brctl.txt 
eth0 
wlan1_1 
wlan1_1.sta1 
+0

它给了我一些开始。虽然阅读第二行仍然存在问题,并且第2,3和4行中的字符数也有所不同。例如[brctl show | tail -n +3 | cut -c 8-]适用于第3行和第4行。但对于第2行不适用。感谢您的回复。 – user27396 2014-12-10 23:52:33

+0

这很奇怪。我在这里使用了'brctl show'(没有界面),所以我不得不测量第一行。由于'tab'字符将标题分开,因此计数是'36'到'interfaces'。然后,我将您的输出复制到一个文本文件并进行测试。由于所有接口之前的空格,因此你想要的列从'46'开始。如果'brctl'在输出中做了一些奇怪的事情,比如'混合制表符和空格',你只需要玩它。另一种方法是'while read -r line'循环,在线测试以确定字符'1-> x'中是否有文本做一件事,否则做另一件事。 – 2014-12-10 23:59:40

+0

尝试我发布的'bash脚本'解决方案。如前所述,我在一个文本文件中测试了您的数据,但由于使用了测试,'brctl show'命令应该可以工作。 – 2014-12-11 00:13:12

0

shell脚本的解决方案,更兼容,故障少的可能性:

#!/bin/sh 
BridgeMembers() 
{ 
    local TheBridge="$1" 
    local CurrentLine="" 
    local CurrentMac="" 
    local CurrentNIC="" 

    IFS="$(printf "\n\b")" ; for CurrentLine in $(brctl showmacs "$TheBridge" | tail -n +2) ; do unset IFS 
     IsLocal="$(OneWord() { echo $3; }; OneWord $CurrentLine)" 
     if [ "$IsLocal" = "yes" ] ; then 
      CurrentMac="$(OneWord() { echo $2; }; OneWord $CurrentLine)" 
      CurrentNic="$(env LANG=en ifconfig | grep -e $CurrentMac)" 
      CurrentNic="$(OneWord() { echo $1; }; OneWord $CurrentNic)" 
      echo "$CurrentNic" 
     fi 
    done 
} 

BridgeMembers "$1" 

请注意,以 “brctl秀” 你没所有时间都没有相同的列宽。