归档具有不同名称的每小时文件

时间:2018-10-08 09:00:15

标签: linux bash

我有一个如下日志文件:

ID

脚本:

Student

这是我到目前为止所获得的帮助,也得到了以下错误:

persist()

我有每小时的日志文件,并且想每天压缩它们,因此如上所述,该压缩文件将被称为logfile_20181008.zip,有没有办法对此不加修改?

1 个答案:

答案 0 :(得分:0)

如果您的未分类日志文件带有这种类型的日志键,那么您的处境会有些不安。可排序的日期时间格式为YYYY[c]MM[c]DD[c]hh[c]mm[c]ss[.sss],并且始终在同一时区中表示。您提供的格式不能通过简单的ascii排序直接排序。作为一个简单的例子。键“ 01/01 / 2018.00:00:00” <“ 01/10 / 2018.00:00:00” <“ 10/10 / 1302.00:00:00”。

使用工具sort,您可以设置复杂的排序结构:

sort -k1.7n,1.10 -k1.4n,1.5 -k1.1n,1.2 -k1.11 <logfile>

这将正确排序文件。现在,您可以将其传送到中以按小时进行拆分:

sort -k1.7n,1.10 -k1.4n,1.5 -k1.1n,1.2 -k1.11 <logfile> \
    | awk -v prefix="logfile_" '{file=substr($1,1,13); gsub(/[^0-9]/,"",file) }
                                {print > (prefix file".txt")}'

这将对文件进行排序并将所有行移至文件logfile_DDMMYYYYhh.txt

更新:问题已更新!

sort log.txt \
 | awk '{file=$1 substr($2,1,2); gsub(/[^0-9]/,"",file) }
        {print > ("bestand_" file ".txt")}'

第二次更新:,因此您现在可以将整个脚本编写为:

#!/usr/bin/env bash

#######################################################
# THIS IS NOT TESTED BUT SHOULD BE UPDATED WHERE NEEDED
#######################################################

# This is your input
logfile="log.txt"

# create a temporary directory where to do all the work
tmpdir=$(mktemp -d)

# get the full path of logfile
logfile=$(readlink -f "$logfile")

cd "$tmpdir" || exit
sort "$logfile" | awk '{file=$1 substr($2,1,2); gsub(/[^0-9]/,"",file) }
                       {print > ("logfile_" file ".txt")}'

# Now you have a $tmpdir with lots of files
# perform the zipping
oldstring=""
newstring=""
for files in ./*; do
   #remove last 6 characters ("hh.txt")
   newstring="${files%[0-9][0-9].txt}"
   [[ "${newstring}" == "${oldstring}" ]] && continue
   zip "$(dirname $logfile)/${newstring}.zip" ${newstring}[0-9][0-9].txt
   oldstring="${newstring}"
done

# uncomment this part only if you are sure it works
# # cleanup
# cd $(dirname $logfile)
# rm -rf "$tmpdir"