我想合并给定日期范围内的多个日志文件。比如我在一个目录下有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_date
和 to_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