tags:

views:

37

answers:

2

Hi, I want to check the modified time of all the files in one directory. If any file has the time different from the current system time, then RED will be printed. Otherwise , GREEN is printed.

ls -lrt| grep main | awk '{if ($8 != date +%R ) print "-->RED"}END{print "-->GREEN"}'

May you suggest me how to correct the above statement. Million thanks.

A: 

this is one way you can do it with shell and date command

#!/bin/bash
current=$(date +%R)
for file in *main*
do
    d=$(date +%R -r "$file")
    if [ "$d" = "$current" ];then
        echo "GREEN: $file, current:$current, d: $d"
    else
        echo "RED: $file, current: $current, d: $d"
    fi
done

note that you will have to adjust to your own needs, since you may just want to compare date only, or time only, etc.. whatever it is, check the man page of date for various date formats.

If you want to do it with awk, here's a pure awk(+GNU date) solution

awk 'BEGIN{
    cmd="date +%R"
    cmd|getline current
    close(cmd)
    for(i=1;i<=ARGC;i++){
        file=ARGV[i]
        if(file!=""){
            cmd="date +%R -r \047"file"\047"
            cmd |getline filetime
            close(cmd)
            if( filetime==current){
                print "GREEN: "file
            }else{
                print "RED: "file
            }
        }
    }
}
' *
ghostdog74
Million thanks. I can modify as follows:ls -lrt | awk 'BEGIN{ cmd="date +%R"; cmd| getline current; close(cmd)}{if $8!= current print "RED"}END{print "GREEN"}'
as one of the posters mentioned, try not to use `ls -ltr` to parse date. On my system, the hour and min is at $7. Also, `ls` sometimes is aliased so it might not work everywhere. Use stat/date to get time stamp.
ghostdog74
+2  A: 

Don't parse the output of ls. You can do what you want with stat.

stat -c%Y file will output the modification time of a file in seconds since Jan 1, 1970. date +%s will output the current time in seconds since Jan 1, 1970.

So, what you want can be done by:

if [[ $(stat -c%Y main) -ne $(date +%s) ]]
then
    echo "RED"
else
    echo "GREEN"
fi

If you want the above for a list of files, and output RED if any time is different:

to_print=GREEN
for f in *main*
do
    if [[ $(stat -c%Y "$f") -ne $(date +%s) ]]
    then
        to_print=RED
        break
    fi
done
echo $to_print

If you're not using bash, then you can replace [[ ]] pair with [ and ], and $(...) with

`...`
Alok
Thanks, but I mean main is keyword
What do you mean "main is keyword"? You are looking for file names matching "main"?
Alok
Oh yes, then I can modified as follows: ls -lrt | awk 'BEGIN{ cmd="date +%R"; cmd| getline current; close(cmd)}{if $8!= current print "RED"}END{print "GREEN"}'Thanks for your concern.