簡體   English   中英

Bash,使用grep,sed或awk提取部分文本,然后進行匹配

[英]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
  • 假設每個段落有1個藍色並且隨機文本不是int
  • 可能有一支班輪(但不太明確)

添加(發布)約束

  • 段落都是從int開始的,沒有其他(如ext 1 ,...)

解釋:

  • 在緩沖區中出現時保持int行
  • 當出現藍色時,添加最后一行(額外的緩沖區,添加2個緩沖區,因此標題比藍色多),打印結果{x;G;p;} (其他操作會根據H;x;pH;g;p不同給出相同的結果H;g;p ,在這種情況下,這是標頭破壞性的,但使用s///可以是保守的
  • 刪除內容(不打印並循環到下一行)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM