Compare Date from FileName and Delete file

I have several files named like this.

Logfile12012012.txt etc.

Now I want to retrieve the date from the file name and delete all files in this directory older than x days. I can retrieve date but it is not comparing.

Here is the code

#!/bin/bash

#THRESHOLD=$(date -d "-1 day" +%d%m%Y)
THRESHOLD=$(date --date='-1 day' +%d%m%Y)
#THRESHOLD=$(date  +%d%m%Y)
echo $THRESHOLD
ls /var/logfiles//LogfileTest????????.txt |
  sed 'h;s/[a-zA-Z.]/ /g;G;s/\n/ /' | 
  while read line1 line2 line3 a b DATE1 FILE e 
do
d2=$DATE1
echo $DATE1
echo $THRESHOLD
d1=$(date -d "$D2" +%d%m%Y)
#echo $d1 
#echo "a"$a
#echo "b"$b
#echo "c"$c 
#echo "d"$d
#echo "e"$e
 
#echo "Line:"$line1
#echo "line2:" $line2 
     [[ $d1 -le $THRESHOLD ]] && ls $FILE

echo $(($THRESHOLD - $d1))
   if  expr  "$d1" "<" "$THRESHOLD"  ; then
echo "hallo"	 
ls $FILE
fi	
  done

Open in new window

LVL 7
jesajaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

simon3270Commented:
You are comparing dates in DDMMYYYY format, but you can't simply compare them.  For example, 10072013 (1th July 2013) will seem to be earlier than 13062012 (13th June 2012).

Change all of your date formats (on lines 4 and 14) to +%Y%m%d.
0
jesajaAuthor Commented:
I thought of that as well but changing the format didn't solve it.
I don't know why
0
simon3270Commented:
You set  $d2, but then use $D2  when calculating $d1 - case matters in shelll variable names.
0
skullnobrainsCommented:
echo $DATE1
echo $THRESHOLD

DATE1=`echo $DATE1 | sed 's/\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)/\3\2\1/'`
THRESHOLD=`echo $THRESHOLD | sed 's/\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)/\3\2\1/'`

test $DATE1 -lt $THRESHOLD && echo BEFORE THRESHOLD
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jesajaAuthor Commented:
thanks, will have to test it next week
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Linux

From novice to tech pro — start learning today.