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.
find
is the right tool for this. Usinggrep
is simply wrong. – Avio May 19 '12 at 16:50ls -l
, which is a bad idea in the first place, and even if you're doing thatgrep
is the wrong tool: it can work, but extracting the date and doing a numerical comparison would be a lot easier. – Gilles 'SO- stop being evil' May 19 '12 at 18:24