Linux 我想使用shell脚本和日志文件位置作为参数,使用所需的命名约定压缩日志文件

Linux 我想使用shell脚本和日志文件位置作为参数,使用所需的命名约定压缩日志文件,linux,shell,Linux,Shell,文件->压缩 参数->日志文件位置 文件\u name.log->文件\u name.log.YYYY-MM-DD.EXECUTIONCOUNT.zip 示例1 21年2月24日执行(DDMMYY) 文件名->ABC.log 输出压缩文件: ABC.log.2021-02-24.1.zip->21年2月24日第一次执行(DDMMYY) ABC.log.2021-02-24.2.zip->21年2月24日第二次执行(DDMMYY) ABC.log.2021-02-24.10.zip->21年2月2

文件->压缩

参数->日志文件位置

文件\u name.log->文件\u name.log.YYYY-MM-DD.EXECUTIONCOUNT.zip

示例1

21年2月24日执行(DDMMYY)

文件名->ABC.log

输出压缩文件:

ABC.log.2021-02-24.1.zip->21年2月24日第一次执行(DDMMYY)

ABC.log.2021-02-24.2.zip->21年2月24日第二次执行(DDMMYY)

ABC.log.2021-02-24.10.zip->21年2月24日第10次执行(DDMMYY)

示例2

21年2月25日执行(DDMMYY)

文件名->ABC.log

输出压缩文件:

ABC.log.2021-02-25.1.zip->21年2月25日第一次执行(DDMMYY)

ABC.log.2021-02-25.2.zip->21年2月25日第二次执行(DDMMYY)

尝试以下操作:

zipfile=$(for i in "$1"*"$(date "+%Y-%m-%d")"*.zip;do echo "$i";done | awk -F\. 'END { if ($4=="") { split($0,map,"*");print map[1]"."strftime("%Y-%m-%d")".1.zip"} else { gsub($4,$4+1,$4);OFS=".";print $0 } }')

# Loop through a listing of the zip files based on the passed parameter $1 and the generated date. Pass the output into awk, setting the field delimiter to "." Take the last entry and replace the number before ".zip" (field 4 - $4) with the field + 1 and print the result, reading the result into the variable zipfile. Use this variable in the actual zip command.
# If this is the first execution, split returned output into the array map and use this to generate the file name.

zip "$zipfile" "$1"

您需要记住某个地方的当前执行计数。如何将其存储在一个隐藏文件
.execution\u count
,并保存到日志文件所在的目录中?由于您需要每个日期和文件名的这些信息,您可以将
.execution\u count
设置为一个隐藏目录,并在该目录中为每个执行日设置一个目录,在这个文件中包含每个日志文件的执行计数?另一种方法是解析当前压缩的文件并从文件名中提取必要的信息。我觉得这更复杂,特别是因为您只想在POSIX shell中执行此操作。此脚本不增加执行计数,只需更新文件。excount=$(对于“$1”日志中的I“$(日期“+%Y-%m-%d”)”*.zip;do echo“$I”;done | tail-1)?为什么还需要执行计数?我已经修改了解决方案,以考虑到没有现有zip文件的第一次执行。在运行修改后的命令时,它会在文件名中增加年份。不用担心,我在脚本注释中添加了更多注释。