user260608
user260608

Reputation:

compare time in awk

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.

Upvotes: 1

Views: 5287

Answers (2)

ghostdog74
ghostdog74

Reputation: 342423

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
            }
        }
    }
}
' *

Upvotes: 1

Alok Singhal
Alok Singhal

Reputation: 96141

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

`...`

Upvotes: 2

Related Questions