如何在bash中使用参数提取文件中的行

时间:2017-10-12 09:31:18

标签: linux bash shell unix sh

我有一个包含所有信息的日志文件。

2017-09-21 02:01:11,130 [http-nio-8080-exec-5] INFO   - Inbound Message
...
...
2017-09-21 09:01:11,130 [http-nio-8080-exec-5] INFO   - Inbound Message
----------------------------
ID: 6044
Address: http://localhost/serveur/Service?wsdl
Encoding: UTF-8
Http-Method: POST
...
2017-09-21 12:01:11,130 [http-nio-8080-exec-5] INFO   - Inbound Message
...

我想仅提取2个日期之间的信息。例如,如果我想要2017-09-21 09 ..和2017-09-21 12之间的信息,我会有这样的事情:

./script.sh 2017-09-21 09 2017-09-21 12
# $1 = 2017-09-21
# $2 = 09
# $3 = 2017-09-21
# $4 = 12
# $1 & 2 are date and hour to begin extract
# $3 & 4 are date and hour to finish extract

我的脚本是这样的。我对shell编程没有了解,但我试图这样做。不幸的是它不起作用

#!/bin/bash

beginLine = "$1 $2"
finishLine = "$3 $4"

while read fileLog.log
do
    if($fileLog.log grep beginLine)
         echo $fileLog.log >> extractedlog.log
    fi
    if($fileLog.log grep finishLine)
         < extractedLog.log;
    fi
done
exit 0;

谁能告诉我问题出在哪里?

2 个答案:

答案 0 :(得分:2)

$ awk '/2017-09-21 09/{a=1};a;/2017-09-21 12/{exit}' input
2017-09-21 09:01:11,130 [http-nio-8080-exec-5] INFO   - Inbound Message
----------------------------
ID: 6044
Address: http://localhost/serveur/Service?wsdl
Encoding: UTF-8
Http-Method: POST
...
2017-09-21 12:01:11,130 [http-nio-8080-exec-5] INFO   - Inbound Message

More alternatives found here

答案 1 :(得分:2)

Short sed approach (matching a range of patterns /.../,/.../):

sed -n '/2017-09-21 09/,/2017-09-21 12/p' logfile

----------

The same can be done with awk (even shorter):

awk '/2017-09-21 09/,/2017-09-21 12/' logfile