Issue
I got a question on the Linux and Shellscript, i know it can`t to get the file from the created date, only the modified dates, but how about , if I got the created date on the files name?
For example, now there are folder which includes some files:
ABCADD01-20230801
ABCADD01-20230802
ABCADD01-20230803
ABCADD01-20230804
ABCADD02-20230801
ABCADD02-20230802
ABCAEE01-20230801
ABCAEE01-20230802
ABCAEE01-20230803
ABCAFF01-20230801
ABCAGG01-20230802
And I need to find the files name is "ABCADD
" and the creation date is "2 days ago or earlier", and zip those files. Today is 20230804
I got an idea is using two for loop:
first loop is finding the files name included "ABCADD
", second loop is finding the creation dated is two days ago.
# Get the date for two days ago
two_days_ago=$(date -d "2 days ago" +%Y%m%d)
# Find the "ABCADD" files that were last modified two days ago, zip them
for file in $(find . -name 'ABCADD*' -type f ); do
for file in $(find . -name '*$two_days_ago' -type f ); do
echo "Zipping $file"
gzip "$file"
done
done
The expected final results should be
ABCADD01-20230801
ABCADD01-20230802
ABCADD02-20230801
ABCADD02-20230802
however, i can't get the "two days ago or earlier" and only able to get the specific day which is 20230802
, and there are still some bugs. any better ways?
Solution
UPDATE
Here's a possible solution in the form of date; find -exec awk | xargs gzip
:
two_days_ago=$(date -d '2 days ago' +%Y%m%d)
find . -name 'ABCADD*-20[0-9][0-9][0-9][0-9][0-9][0-9]' \
-exec awk -v max="$two_days_ago" '
BEGIN {
for ( i = 1; i < ARGC; i++ ) {
n = split(ARGV[i], a, "-");
if ( a[n] <= max)
printf("%s%c", ARGV[i], 0);
}
exit;
}
' {} + |
xargs -0 gzip
Answered By - Fravadona Answer Checked By - Senaida (WPSolving Volunteer)