Linux Bash Shell字串抽取、按列合并和格式化輸出

來源:互聯網
上載者:User

標籤:bash shell   格式化輸出   字串抽取   按列合并   

需求來源:預設的ip link show命令輸出會輸出系統中已經存在的網卡(包括虛擬網卡)的名稱、MAC地址、連接埠狀態等資訊,但也夾雜著一些無用的資訊,此次的字串操作就是將這些資訊中的網卡名稱、MAC地址、連接埠狀態取出來。

涉及到的知識包括:常用的字串的處理工具awk、sed、cut等的用法,paste按列合并,printf格式化輸出等。

例如原輸出資訊為:

650) this.width=650;" title="image" style="border-top:0px;border-right:0px;border-bottom:0px;border-left:0px;" border="0" alt="image" src="http://s3.51cto.com/wyfs02/M01/59/6D/wKiom1TSx9vigKKoAAMLjctETp8043.jpg" height="304" />

現在要把中紅色框內的資訊全部提取出來,但痛點在於ip link show命令的預設輸出會將MAC地址列印在下一行,導致普通的awk操作無法按照列提取。

但辦法總是有的:

方法1:使用awk,藉助if else判斷,數字開頭的行取所需的列,不是數字開頭的行輸出所需的列,一起列印出來就會得到所需要的結果。

ip link show | awk ‘{if($0~/^[0-9]+:/)printf( "%-15s%-15s",$2,$9);else print $2}‘

650) this.width=650;" title="image" style="border-top:0px;border-right:0px;border-bottom:0px;border-left:0px;" border="0" alt="image" src="http://s3.51cto.com/wyfs02/M02/59/6A/wKioL1TSyMfTDvd6AAG91er_wBQ786.jpg" height="303" />

方法2:使用awk或cut,將每一行中所需的列提取出來,再將這些列按照列合并起來(但此種方法繁瑣,而且格式化輸出不容易,需要最後格式化輸出)。

INTERFACE_NAME=`ip link show | grep ^[1-90-9] | cut -d ":" -f 2`   MAC_ADDRESS=`ip link show | grep -v ^[1-90-9] | cut -d " " -f 6`    STATE=`ip link show | grep ^[1-90-9] | cut -d " " -f 9`temp=`paste <(echo "$INTERFACE_NAME") <(echo "$MAC_ADDRESS")`paste <(echo "$temp") <(echo "$STATE")temp2=`paste <(echo "$temp") <(echo "$STATE")`echo "$temp2" | awk ‘{printf("%-15s%-20s%-15s\n",$1,$2,$3)}‘

650) this.width=650;" title="image" style="border-top:0px;border-right:0px;border-bottom:0px;border-left:0px;" border="0" alt="image" src="http://s3.51cto.com/wyfs02/M00/59/6A/wKioL1TSyMfxZzN1AAJJVeroVF8698.jpg" height="371" />

方法3:將ip link show命令輸出格式化,將MAC地址列印在同一行。

650) this.width=650;" title="image" style="border-top:0px;border-right:0px;border-bottom:0px;border-left:0px;" border="0" alt="image" src="http://s3.51cto.com/wyfs02/M00/59/6D/wKiom1TSx9zCqJ5fAAU-t8DKujM264.jpg" height="282" />

使用ip的-o參數,將輸出控制在同一行。參數等同於“-oneline”,意思就是同一行,解釋如所示,早已經考慮好了,這種設計實在令人唏噓不已!

“output each record on a single line, replacing line feeds with the ’\′ character. This is convenient when you want to count records with wc(1) or to grep(1) the output.”

--END--

本文出自 “通訊,我的最愛” 部落格,請務必保留此出處http://dgd2010.blog.51cto.com/1539422/1611783

Linux Bash Shell字串抽取、按列合并和格式化輸出

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.