linux - shell 脚本 : Merge files from within a date range

标签 linux bash shell date unix

<分区>

我想合并给定日期范围内的多个日志文件。比如我在一个目录下有5天的日志文件:

server.log.2016-04-14-00 
server.log.2016-04-14-01
. . .
server.log.2016-04-18-23
server.log.2016-04-19-00
server.log.2016-04-19-01

我知道我可以使用 cat 来合并文件,但是我如何在 shell 脚本中编写代码以便仅选择 2016-04-17-22 和 2016-04-18-01 之间的文件?

最佳答案

以下脚本接受服务器的日志文件作为其第一个参数。 两个重要的变量是 from_dateto_date,它们控制 from-to 范围。它们硬编码在脚本中,您可能希望更改它以增强脚本的使用灵 active 。

#!/bin/bash

# Server's log file.
server_log_file=$1
# The date from which the relevant part of the log file should be printed.
from_date='2016/04/14 00:00'
# The date until which the relevant part of the log file should be printed.
to_date='2016/04/19 01:00'

# Uses 'date' to convert a date to seconds since epoch.
# Arguments: $1 - A date acceptable by the 'date' command. e.g. 2016/04/14 23:00
date_to_epoch_sec() { 
    local d=$1
    printf '%s' "$(date --date="$d" '+%s')"
}

# Convert 'from' and 'to' dates to seconds since epoch.
from_date_sec=$(date_to_epoch_sec "$from_date")
to_date_sec=$(date_to_epoch_sec "$to_date" )

# Iterate over log file entries.
while IFS=. read -r s l date; do
    # Read and parse the date part.
    IFS=- read -r y m d h <<< "$date"
    # Convert the date part to seconds since epoch.
    date_sec=$(date_to_epoch_sec "$y/$m/$d $h:00")

    # If current date is within range, print the enire line as it was originally read.
    if (( date_sec > from_date_sec && date_sec < to_date_sec )); then
        printf '%s.%s.%s\n' "$s" "$l" "$date"
    fi

done < "$server_log_file"

为了测试它,我创建了以下文件,命名为logfile:

server.log.2016-04-14-00
server.log.2016-04-14-01
server.log.2016-04-18-23
server.log.2016-04-19-00
server.log.2016-04-19-01

使用示例(脚本名为sof):

$ # Should print logs from 2016/04/14 00:00 to 2016/04/19 01:00 
$ ./sof logfile 
server.log.2016-04-14-01
server.log.2016-04-18-23
server.log.2016-04-19-00

关于linux - shell 脚本 : Merge files from within a date range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36731062/

相关文章:

linux - 如何使用 shell 脚本运行 2 个命令

Node.js 与 Git Bash (MINGW64)

linux - 如何从 Apache 调用 shell 脚本?

linux - 为什么最新版本的 sys-stat 在杀死后不显示平均值?

c - 使用 NASM 构建 KMP 前缀

bash - 如何将两个单独的脚本组合在一起以制作一个脚本而不是两个?

mysql - 在 shell 脚本中嵌入 MySQL

java - JSVC 初始化脚本不退出

linux - 多线程fork

perl - uniq 主机名的内核版本