hades
hades

Reputation: 4696

Shell script tar specific files with retention period

I am new to Unix Shell script. I need to keep file for retention period of one month and archive other.

Example:

File format: WE20160225.log (20160225 YYYYMMDD)

Say in the directory /oracle/Sales has 3 files:

WE20160130.log

WE20151201.log

WE20151109.log

I need to tar.gz the WE20151201.log and WE20151109.log

But not WE20160130.log because the file is less than one month from now. How can I do this? (probably need to substring the filename)

I'm able to change directory but don't know what to do next. My logic is loop through the file and substring the date from file and check with current date

I need to use the filename date, not the file modification date.

SALES_DIR="/oracle/sales/"
cd $SALES_DIR

Upvotes: 1

Views: 1363

Answers (2)

anubhava
anubhava

Reputation: 785146

You can use this for loop:

curr=$(date '+%s')
for file in WE*.log; do
   f="${file%.*}"
   ts=$(date -d "${f:2}" '+%s')
   (( (curr - ts) > 30*86400 )) && echo "$file"
done | tar cvzf backup.tgz -T-

Basically we are getting current date-time in unix seconds and then extracting date from file and finding it's EPOCH (unix ts) value using date.

Finally we are comparing difference of 2 timestamps with 30*86400 (30 days) and printing the filename. Whole thing is piped to a tar command to create a tar zipped file.

Upvotes: 2

Hélio Nagamachi
Hélio Nagamachi

Reputation: 21

Probably something along those lines:

list=`ls *.log`

limit=`date --date 'Last Month' +%Y%m%d`

for filename in $list
  do
    if [ ${filename:2:8} -lt $limit ]
      then
        tar -czf "$filename.tar.gz" $filename
      fi
  done;

Upvotes: 2

Related Questions