Bash – Rename Multiple files gzips them and delete older than 10 days

bashfilesgziprenamescripting

I'm new to Linux/Unix and slowly learning it step by step. Unfortunately on today’s job interview was surprised by a task to do (which of course I didn’t know). I was asked to prepare a bash script that:

  • changes the names of .log. files to (name).(date).log.(remaining part of the original name) and gzips them to a .gz archive.

  • deletes (name).(date).log.(remaining part of the original name).gz files older than 10 days.

Never too late for asking and would really appreciate if you could let me know how it should look like.

Best Answer

Assuming GNU tools, I'd do something like

find . -type f \( -name '*.[0-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9].log.*.gz' \
       \( -mtime -10 -o -delete -o -true \) -o -name '*.log.*' ! -name '*.gz' \
       \( -mtime +9 \( -delete -o -true \) -o -printf '%TF/%p\0' \) \) |
  while IFS=/ read -rd '' date file; do
    basename=${file##*/}
    dirname=${file%/*}
    newfile=$dirname/${basename%.log.*}.$date.log.${basename##*.log.}
    mv "$file" "$newfile" && gzip "$newfile"
  done
Related Question