3

We have a directory contains files which contains time in their filename

./test.2013-06-11_06-01.gz
./test.2013-06-12_01-01.gz
./test.2013-06-13_03-01.gz
./test.2013-06-14_03-01.gz
./test.2013-06-15_04-01.gz

How to list files if their filename are more than N days before?

3
  • 1
    What does 06-01, 01-01,... mean?
    – cuonglm
    Jun 20 '13 at 3:52
  • @Gnouc - could it be the time? in the date_time format...
    – rahuL
    Jun 20 '13 at 4:11
  • Does the file create/modify time reflects the same date than the filename?
    – ghm1014
    Jun 20 '13 at 22:27
2

How about something like this?

maxdate=$(date -d "5 days ago" "+%Y-%m-%d");
for fn in *.gz; do
    [ "$fn" ">" "test.${maxdate}_99-99.gz" ] || echo $fn
done

I'm ignoring the part of the filename after the date (time, presumably?), but it would be fairly easy to modify this to consider that part of the filename as well if needed.

This answer is based off of a similar question on Stack Overflow: https://stackoverflow.com/questions/2443078/filtering-filenames-with-bash

2
  • What is the magic "99-99" in your scripts?
    – Howard
    Jun 22 '13 at 4:32
  • @Howard, I didn't know what the last two numbers in the filename were for, so I used the max value for those in order to get consistent behaviour. If I had omitted them or used 00-00, filenames that exactly matched the date we got for "5 days ago" would have been skipped because "test.2013-06-12_01-01.gz" > "test.2013-06-12"
    – jcsanyi
    Jun 22 '13 at 4:39
1

You can use date command to find date of N days before, then using grep to search in your text file.

grep `date +%Y-%m-%d -d "5 days ago"` test.txt

test.txt:

./test.2013-06-11_06-01.gz
./test.2013-06-12_01-01.gz
./test.2013-06-13_03-01.gz
./test.2013-06-14_03-01.gz
./test.2013-06-15_04-01.gz

ouput:

./test.2013-06-15_04-01.gz

Today is 20/06/2013, 5 days ago is 15/06/2013.

Update

The final solution, I use a small script:

#!/bin/bash

FILE=$1
tmp="/tmp/tmp_$$.txt"
tmp1="/tmp/tmp1_$$.txt"
maxday=$2

cp $FILE $tmp

for i in `seq 1 $maxday`
do
    date_point=`date +%Y-%m-%d -d "$i days ago"`
    grep -v "$date_point" $tmp > $tmp1
    cp $tmp1 $tmp
done

echo "Files match:"
cat $tmp
rm -rf $tmp
rm -rf $tmp1

This script will remove all file N days ago upto now from output, so if you want to find all file older than N days, you must define maxday = N - 1, i.e if you want to file that older than 8 days:

./test.sh test.txt 7

Ouput:

Files match:
./test.2013-06-11_06-01.gz
./test.2013-06-12_01-01.gz
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.