0

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. This is what I've done by now:

#!/bin/bash

#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]+?)
time_1=$[$time_-1]
time_2=$[$time_-2]

#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.

3
  • 6
    Why do you want to use grep for this? It is not the right tool at all.
    – Mat
    Commented May 19, 2012 at 14:19
  • find is the right tool for this. Using grep is simply wrong.
    – Avio
    Commented May 19, 2012 at 16:50
  • 2
    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. Commented May 19, 2012 at 18:24

1 Answer 1

3

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)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .