Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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

share|improve this question

migrated from serverfault.com Jun 20 '13 at 6:49

This question came from our site for system and network administrators.

marked as duplicate by manatwork, Anthon, Tshepang, slm, Mat Jun 21 '13 at 12:15

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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... – i.h4d35 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

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

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: http://stackoverflow.com/questions/2443078/filtering-filenames-with-bash

share|improve this answer
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

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





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


The final solution, I use a small script:



cp $FILE $tmp

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

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


Files match:
share|improve this answer

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