Joel Deleep
Joel Deleep

Reputation: 1398

Comparing file created yesterday with file created today

I have files in a directory as shown in the below format.

$today and $yesterday are two variables holding today's date and yesterday's date , both will hold date as shown in below structure .
today=$(date +"%Y-%m-%d")
yesterday=$(date -d "yesterday 13:00" '+%Y-%m-%d')

example-$today.txt
polar-$today.txt
example-$yesteday.txt
polar-$yesteday.txt

Example yesterday : example-2020-09-24.txt
Example today: example-2020-09-25.txt

Files are created on a daily basis using cronjob , so there will be files in below structure with tomorrow's date.

example-$tomorrow.txt
polar-$tomorrow.txt

I want to compare files starting with same name on different dates and if there is difference execute a python script.The python script takes today's file as first argument if there is a difference.

if diff example-$today.txt example-$yesteday.txt
then 
echo "No difference"
else
python script.py example-$today.txt
fi

If I have only 2 or 3 files I can use if else code for each file using diff as mentioned above, but the list will be populated with more unique names in future , and writing if command is tedious.

Requirement :

Compare all the txt files in the directory with same named file names on yesterday and today , if there is a difference execute the python script.

Upvotes: 1

Views: 329

Answers (1)

William Pursell
William Pursell

Reputation: 212198

Seems like it's probably not too terrible to do:

for base in example polar; do
    if ! diff ${base}-$today.txt ${base}-$yesteday.txt; then    
        python script.py ${base}-$today.txt
    fi
done

That should be fairly maintainable, and you can write list='example polar ...' ... for base in $list, or list=$( cmd to dynamically generate names), or use an array. There's a lot of flexibility. For example, if you don't want to maintain the list of files, you could do:

for file in *-${today}.txt; do 
    base="${file%-${today}.txt}"
    if ! diff "${base}-$today.txt" "${base}-$yesteday.txt"; then    
        python script.py "${base}-$today.txt"
    fi
done

Note that I've removed the excess verbosity. Succeed quietly, fail loudly.

Upvotes: 1

Related Questions