如何从连续yyyy-mm-dd格式的报告中提取详细信息,直到下一个yyyy-mm-dd条目在unix中创建

时间:2015-03-05 07:28:04

标签: linux shell unix

我有一个报告(report.log),其中包含这样的条目

Following are access details for date: 2015-02-18
---------------------------------------------------

details1   
details2    
....   
....

Following are access details for date: 2015-02-19
----------------------------------------------------

line1                                                                        
line2   
....  
....

Following are access details for date: 2015-02-20
-------------------------------------------------------

line1                                                                        
line2   
....  
....

我想编写一个脚本,要求输入yyyy-mm-dd格式的单个日期(输出应该是以下是日期的访问详细信息:yyyy-mm-dd,直到和排除新的输入行“以下是日期“)的访问详情或类似于2014-02-09至2014-02-20的范围(此输出应为以下是日期的访问详情:2014-02-09至2014年范围内的第二个日期-02-20),这意味着输出从日期范围的第一个日期到最后一个日期开始的所有条目。

请注意以下内容之前和之后的新行是......报告中的行

1 个答案:

答案 0 :(得分:0)

这是一个使用d1=$(date -d "somedate" +%s)将秒转换为纪元的快速示例。然后是第二天d2=$((d1 + 86400))。这允许您在包含第一个日期的文件中找到该行并读取所有行,直到找到第二天。如果您有任何问题,请与我们联系:

#!/bin/sh

dt1=$(date -d "$1" +%s)   # date provided by input
dt1f=$(date -d @$dt1 +%F) # date1 formatted in YYYY-MM-DD
dt2=$((dt1 + 86400))      # add one day to it
dt2f=$(date -d @$dt2 +%F) # date2 formatted in YYYY-MM-DD

ifn=${2:-loghdg.txt}      # input file

# printf "\nDate Range: %s - %s\n\n" "$(date -d @$dt1 +%F)" "$(date -d @$dt2 +%F)"
printf "\nDate Range: %s - %s\n\n" "$dt1f" "$dt2f"

# read each line in file
while read -r line; do

    arr=( $line )                   # read line into array
    for i in ${arr[@]}; do          # for each word in line
        [ $i == $dt1f ] && found=1  # if date1 found, print lines
        [ $i == $dt2f ] && found=0  # if date2 found, stop printing
    done

    [ "$found" == "1" ] && printf " %s\n" "$line"

done <"$ifn"

输入文件

$ cat loghdg.txt
Following are access details for date: 2015-02-18
details1
details2
....
....
Following are access details for date: 2015-02-19
line1
line2
....
....
Following are access details for date: 2015-02-20
line1
line2
....
....

<强>输出/使用

$ sh date-day-diff.sh 2015-02-18

Date Range: 2015-02-18 - 2015-02-19

 Following are access details for date: 2015-02-18
 details1
 details2
 ....
 ....

接受startend日期的修改非常简单。

已修改为接受开始日期+结束日期

dt1=$(date -d "$1" +%s)   # start date provided by input
dt1f=$(date -d @$dt1 +%F) # date1 formatted in YYYY-MM-DD
dt2=$(date -d "$2" +%s)   # end date provided by input
dt2f=$(date -d @$dt2 +%F) # date2 formatted in YYYY-MM-DD

ifn=${3:-loghdg.txt}      # input file

新输出

$ sh date-day-diff.sh 2015-02-18 2015-02-20

Date Range: 2015-02-18 - 2015-02-20

 Following are access details for date: 2015-02-18
 details1
 details2
 ....
 ....
 Following are access details for date: 2015-02-19
 line1
 line2
 ....
 ....