How to list a file by filename as a date?

93 views Asked by At

I have list of filename which have format like this _ddmmyyyy.txt for example :

filea_01122016.txt
filea_02122016.txt
filea_03122016.txt
filea_04122016.txt
filea_05122016.txt

And I want to compress those file from sysdate - 3 days in my RHEL environment. Assume today is 5 Dec 2016 and I want compress those file start from date 2 dec, 1 dec backward. Because the date that Im using is from the file name not the timestamp of file created(by system).

I read some tutorial that they are using find utility but in my case Im using date from the filename.

I already make some mechanism like this for compressing text in a whole month

dir=`date '+%Y%m%d'`

tanggal=`date --date="$(date +%Y-%m-15) -1 month" '+%Y%m'`

base=/inf_shr/ProcessedSrc/CDC/ARCHIVE/F_ABC
cd $base

mkdir $dir
cp ../../F_CC/*${tanggal}* $dir

tar cvf - $dir | gzip -9 - > ${tanggal}_F_CC.tar.gz

rm -rf $dir
rm -rf ../../F_CC/*${tanggal}*

Now I want compress for file with sysdate - 3 days *)sorry for my english

And idea for the code? thank you

1

There are 1 answers

4
sjsam On BEST ANSWER

TL;DR but below would be my approach

$ ls # listing the initial content
filea_17122016.txt  filea_19122016.txt  filea_21122016.txt
filea_18122016.txt  filea_20122016.txt  script.sh
$ cat script.sh  # Ok, here is the script I wrote
#!/bin/bash
now="$(date +%s)"
for file in filea_*
# Mind, if recursive globbing required put ** instead of *
# after you do set -s globstar
do
  date=${file#filea_}
  date=${date%.txt}
  y=$(cut -b 5- <<<"$date") # We use cut to trim year month and date separately
  m=$(cut -b 3-4 <<<"$date")
  d=$(cut -b 1-2 <<<"$date")
  date=$(date -d "$y-$m-$d" +%s) # Calulating the time in seconds from epoch, using the date string where we use the above calculated values
  dif=$(( (now-date)/(3600*24) )) #Calculating the difference in dates
  if [ "0$dif" -ge 3 ]
  then
    zip mybackup.zip "$file" #If the file is 3 or more days old, the add it to zip
    #Note if the zip file already exists, files will be appended
    rm "$file" # remove the file
  fi
done
$ ./script.sh # Script doing its job
  adding: filea_17122016.txt (stored 0%)
  adding: filea_18122016.txt (stored 0%)
$ unzip -l mybackup.zip  #listing the contents of the zip file
Archive:  mybackup.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2016-12-21 11:38   filea_17122016.txt
        0  2016-12-21 11:38   filea_18122016.txt
---------                     -------
        0                     2 files
$ ls # listing the left over content, which includes the newly created zip
filea_19122016.txt  filea_21122016.txt  script.sh
filea_20122016.txt  mybackup.zip
$ # Job done