Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Filenames with bash

Tags:

bash

shell

I have a directory full of log files in the form

${name}.log.${year}{month}${day}

such that they look like this:

logs/
  production.log.20100314
  production.log.20100321
  production.log.20100328
  production.log.20100403
  production.log.20100410
  ...
  production.log.20100314
  production.log.old

I'd like to use a bash script to filter out all the logs older than x amount of month's and dump it into *.log.old

X=6  #months

LIST=*.log.*;
for file in LIST; do
  is_older = file_is_older_than_months( ${file}, ${X} );
  if is_older; then
    cat ${c} >> production.log.old;
    rm ${c};
  fi
done;

How can I get all the files older than x months? and... How can I avoid that *.log.old file is included in the LIST attribute?

like image 557
Stefan Avatar asked Jan 22 '23 10:01

Stefan


1 Answers

The following script expects GNU date to be installed. You can call it in the directory with your log files with the first parameter as the number of months.

#!/bin/sh

min_date=$(date -d "$1 months ago" "+%Y%m%d")

for log in *.log.*;do
        [ "${log%.log.old}"     "!=" "$log" ] && continue
        [ "${log%.*}.$min_date" "<"  "$log" ] && continue
        cat "$log" >> "${log%.*}.old"
        rm "$log"
done
like image 97
mdom Avatar answered Jan 25 '23 00:01

mdom