【问题标题】:How to extract lines from a file using parametres in bash [duplicate]如何使用bash中的参数从文件中提取行[重复]
【发布时间】:2017-10-12 09:31:17
【问题描述】:

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

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
...

我只想提取两个日期之间的信息。例如,如果我想要 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;

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

【问题讨论】:

  • 这不是bash 语法

标签: linux bash shell unix sh


【解决方案1】:
$ 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

找到更多替代品here

【讨论】:

    【解决方案2】:

    sed方法(匹配一系列模式/.../,/.../):

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

    ---------

    awk(甚至更短)也可以做到这一点:

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

    【讨论】:

    • 并在匹配 2017-09-21 12 后退出进程我应该使用 /q 是吗?
    • @Chinovski,不,在这种情况下不是。此处不应添加q
    • @tripleee,所有扩展案例都应该在问题中进行描述和阐述。任何人都可以发明越来越多的扩展条件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    相关资源
    最近更新 更多