2016-04-06 34 views
0

使用命令行工具,我需要提取文本「HTTP」,(或任何協議恰好是),關鍵字「檢測的協議」之後:如何在Linux中提取文件的特定行和列?

部分文件內容:

Detected protocol: 
     HTTP 1254 

完整的文件內容:

nDPI Memory statistics: 
    nDPI Memory (once):  103.29 KB  
    Flow Memory (per flow): 1.91 KB  
    Actual Memory:   1.76 MB  
    Peak Memory:    1.76 MB  

Traffic statistics: 
    Ethernet bytes:  1342   (includes ethernet CRC/IFC/trailer) 
    Discarded bytes:  0    
    IP packets:   10   of 10 packets total 
    IP bytes:    1102   (avg pkt size 110 bytes)   


Detected protocols: 
    HTTP     packets: 10   bytes: 1102   flows: 1    


Protocol statistics: 
    Acceptable     1102 bytes 
+0

我會建議使用多行sed' - 見[這裏](http://superuser.com/a/634848/438726),或者如果你需要更多的控制,'awk'。 – urban

+0

您剛剛給出的此示例輸入的預期輸出是什麼?嘗試閱讀[問]在這裏有更好的體驗。 – fedorqui

回答

0

假設你只是希望這一次發生的,比如,你可以說:

awk 'matched {print $2; exit} /Detected protocol/ {matched=1}' file 

它返回:

1254 

此檢查是一個行包含 「檢測到協議」。如果是這樣,它會設置一個標誌,在下一行中提示打印。然後,它退出。

您還可以在字段分隔符設置爲HTTP

awk -F"HTTP" 'f {print $2; exit} /Detected protocol/ {f=1}' file 

它返回更新後的輸入文件如下:

    packets: 10   bytes: 1102   flows: 1 
+0

發生了以下錯誤:awk:cmd。行:1:匹配{print $ 2;退出} /檢測到的協議/ {匹配= 1} awk:cmd 。行:1:^語法錯誤 awk:cmd。行:1:匹配{print $ 2;退出} /檢測到的協議/ {匹配= 1} awk:cmd 。行:1:^語法錯誤 – user3728748

+0

@ user3728748這是我的錯,因爲我使用'match'作爲變量名,而它是一個保留字。將其更改爲「awk」匹配{print $ 2;退出} /檢測到的協議/ {匹配= 1}'文件'。 – fedorqui

0

你也可以使用

sed -n '/Dectected protocol/{n;p}' $file 
相關問題