2016-04-19 22 views
1

指定した期間内に複数のログファイルをマージしたいと思います。私はファイルをマージするために猫を使用することができますが、例えば、間になるようにファイルのみどのように私はシェルスクリプトでコーディングすることができます知ってシェルスクリプト:日付範囲内のファイルをマージする

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 

:たとえば、私は、ディレクトリ内のログファイルの5日間を持っています、2016-04-17-22および2016-04-18-01が選択されていますか?

+1

を検索機能を使用する方法を学ぶ**前に**質問する。 '[bash] log file filter'を検索すると6個の項目が返され、' [bash] log file'は4000個以上を返します。見てください;-) ...幸運。 – shellter

+0

@ChrisC日付の形式はyyyy-mm-dd-hhですか? –

+0

はい、ログファイル名に使用される日付形式です。 –

答えて

1

次のスクリプトは、サーバーのログファイルを最初の引数として受け入れます。 2つの重要な変数はfrom_dateto_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