[英]Bash, Using grep, sed or awk to extract section of text and then match
我有一個文本文件,想提取所有匹配“藍色”的接口
random text random text random text
random text random text
int 1
random text
blue
random text
random text
int 2
random text
random text
red
random text
int 3
random text
random text
random text
blue
random text
random text
int 4
blue
random text
int n
random text
value
random text
random text random text random text
random text random text
想要的輸出:
int 1
blue
int 3
blue
int 4
blue
int n
blue
(注意,int 2為“紅色”,因此不顯示)
我試過了:grep“ int” -A n file.txt | grep“ blue”,但只顯示與“ blue”匹配的行。 我還要顯示匹配“ int”的行。 另外,段的長度可以變化,因此使用-A n並沒有用。
一個awk解決方案可能是以下幾種:
awk '/^int/{interface = $0} /blue/{print interface; print $0}' input.txt
它總是保存最新發現的接口。 如果找到blue
,它將打印存儲的接口和包含blue
的行。
另一個sed解決方案
適用於多個藍調
sed -n '/^int/{x;/blue/{p;d}};/blue/H' file
random text random text random text
random text random text
int 1
random text
blue
blue
random text
random text
int 2
random text
random text
red
random text
int 3
random text
random text
random text
blue
random text
random text
int 4
blue
blue
blue
blue
blue
random text
int n
random text
value
random text
random text random text random text
random text random text
int 1
blue
blue
int 3
blue
int 4
blue
blue
blue
blue
blue
一種可能的GNU sed解決方案
sed -n '/^int\|blue/p' file | sed -r ':a; N; $! ba; s/int \w*\n(int)/\1/g; s/int \w*$//'
輸出
int 1
blue
int 3
blue
int 4
blue
sed '/^int/ h
/^[[:space:]]*blue/ {x;G;p;}
d
' YourFile
添加(發布)約束
解釋:
{x;G;p;}
(其他操作會根據H;x;p
或H;g;p
不同給出相同的結果H;g;p
,在這種情況下,這是標頭破壞性的,但使用s///
可以是保守的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.