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

 

    脚本运行结果以下:

相关文章
相关标签/搜索