Ronit Shrivastava
Ronit Shrivastava

Reputation: 41

I want to zip the log files with a desired naming convention using shell script with the log file location as an argument

File -> zip

Argument -> Log file location

File_name.log -> File_name.log.YYYY-MM-DD.EXECUTIONCOUNT.zip

Example 1

Execution on 24/02/21(DDMMYY)

File name -> ABC.log

Output zip file:

ABC.log.2021-02-24.1.zip -> 1st Execution on 24/02/21(DDMMYY)

ABC.log.2021-02-24.2.zip -> 2nd Execution on 24/02/21(DDMMYY)

ABC.log.2021-02-24.10.zip -> 10th Execution on 24/02/21(DDMMYY)

Example 2

Execution on 25/02/21(DDMMYY)

File name -> ABC.log

Output zip file:

ABC.log.2021-02-25.1.zip -> 1st Execution on 25/02/21(DDMMYY)

ABC.log.2021-02-25.2.zip -> 2nd Execution on 25/02/21(DDMMYY)

Upvotes: 0

Views: 235

Answers (1)

Raman Sailopal
Raman Sailopal

Reputation: 12887

Try the following:

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"

Upvotes: 1

Related Questions