次のスクリプトは、サーバーのログファイルを最初の引数として受け入れます。 2つの重要な変数はfrom_date
とto_date
で、範囲はからまでです。スクリプト内でハードコーディングされているため、スクリプトの使用の柔軟性を高めるためにこれを変更したい場合があります。
#!/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"
それをテストするために、私はログファイルという名前の次のファイルを、作成した:
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
を検索機能を使用する方法を学ぶ**前に**質問する。 '[bash] log file filter'を検索すると6個の項目が返され、' [bash] log file'は4000個以上を返します。見てください;-) ...幸運。 – shellter
@ChrisC日付の形式はyyyy-mm-dd-hhですか? –
はい、ログファイル名に使用される日付形式です。 –