Shell提取日誌文件指定關鍵詞之間的段落,且包含指定內容

有時候相似於這樣的日誌:bash

A日誌

12345file

Bgrep

Aim

sadasfd腳本

Bword

Aimg

12345
asfdsa文件

Bwhile


想要把從A開始,到B結束,中間包含「12345」的段落取出來,獲得下面的結果:

A

12345

B


A

12345
asfdsa

B

怎麼辦呢?請看腳本(腳本中是逐行讀取日誌文件):

 

#!/bin/bash
start_key="A"    # 段落開始標識
keyword="12345"    # 段落之間包含的關鍵詞
end_key="B"    # 段落結束標識
logfile="/tmp/log.txt"   #  日誌文件
filename="/tmp/result.txt"    # 提取內容保存文件
tmpfile="/tmp/tmpfile.txt"   # 臨時文件(過渡文件)

rm -f $filename $tmpfile

cat $logfile | while read line
do
    if [ -s "$tmpfile" -a "$line " != "$start_key" ];then
        if [ "$line" != "$end_key" ];then
            echo "$line" >> $tmpfile
        else
            if [ `cat $tmpfile | grep -c "$keyword"` -ne 0 ];then
                cat $tmpfile >> $filename
                echo -e "${end_key}\n" >> $filename
            fi
            rm -f $tmpfile
        fi
    fi
    if [ ! -s "$tmpfile" ];then
        if [ "$line" == "$start_key" ];then
            echo "$line" >> $tmpfile
        fi
    fi
done

 

    腳本運行結果以下:

相關文章
相關標籤/搜索