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

I'd like to make a list to stdout of the files modified in the last two hours in the . directory using grep. It has to be automatic (can't ask user what time is it or similar stuff) and I have to use only grep, not conditional statements. I don't know even if it is possible but I'm pretty curious. This is what I've done by now:


#redirect output to a file otherwise grep will read all as one line not giving a readable   output
ls -lrt > ls_out
date > date_extr

# extract hour from date. E interpret what follows as an extended regex. o print only what is matched. m 1 stop after one match
#I'll go back 2 hours
time_=$(date | grep -Eo [0-9]+?: | grep -Eom 1 [0-9]+?)

#grep day and month from the previous file "" to include spaces in date_
date_=$(grep -oE [0-9]+\ [A-Za-z]+\  date_extr)
grep "$date_" ls_out > ls_date

#match time as it is if it has 2 digits for example 11, 19, 21. \ number avoid matches as 19: if time_ is 9:
grep \ $time_:      ls_date
grep \ $time_1:     ls_date
grep \ $time_2:     ls_date

#match 09: if time_ output was 9:
grep 0$time_:      ls_date
grep 0$time_1:     ls_date
grep 0$time_2:     ls_date

#cleaning up
rm ls_out ls_date date_extr

It works fine, the only problem is that it doesn't list files modified the day before if the script is run at 00 or 1 a.m.

The problem is that ii should grep the date AND the output of ls -lrt and I seem to need an if.

In case you are asking the reason of this question, it is the link where I take it with some modifications: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_04_05.html. Question number 7.

Thank you for your time

share|improve this question
Why do you want to use grep for this? It is not the right tool at all. – Mat May 19 '12 at 14:19
find is the right tool for this. Using grep is simply wrong. – Avio May 19 '12 at 16:50
My take on this is that this is simply a bad question. Skip it. I suppose the intent is to make you parse the output of ls -l, which is a bad idea in the first place, and even if you're doing that grep is the wrong tool: it can work, but extracting the date and doing a numerical comparison would be a lot easier. – Gilles May 19 '12 at 18:24

Use find . -maxdepth 1 -mmin -120. If you absolutely must use grep you can grep for an empty string: grep -l '' $(find . -maxdepth 1 -mmin -120)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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