You could do this:
- extract the year/month/day values into a shell variable,
- create a temporary file
- use the
touch
command (adding 0s for hour/minute/second) to set the modification date for the temporary file
Because your question is about bash
, you likely are using Linux. The test
program used in Linux (part of coreutils) has extensions for timestamp comparison (-nt
and -ot
) not found in POSIX test
.
POSIX comments about this in the rationale for test
:
Some additional primaries newly invented or from the KornShell appeared in an early proposal as part of the conditional command ([[]]
): s1 > s2, s1 < s2, str = pattern, str != pattern, f1 -nt f2, f1 -ot f2, and f1 -ef f2. They were not carried forward into the test utility when the conditional command was removed from the shell because they have not been included in the test utility built into historical implementations of the sh utility.
Using that extension, you could then
- create another temporary file with the date you want to compare against
- use the
-nt
operator in test
to make the comparison you asked for.
Here is an example. A clarification by OP mentioned the platform, so one could use stat
as an alternative to temporary files (compare OSX and Linux):
#!/bin/bash
# inspect each file...
with_tempfile() {
echo "** with temporary file $name"
test=$MYTEMP/$name
touch -t $date $test
[ $name -nt $test ] && echo "...newer"
}
# alternatively (and this is system-dependent)
with_stat() {
echo "** with stat command $name"
stat=$(stat -t "%Y%m%d%H%M" -f "%Sm" $name)
[ $stat -gt $date ] && echo "...newer"
}
MYTEMP=$(mktemp -d /var/tmp/isnewer.XXXXXX)
trap "rm -rf $MYTEMP" EXIT
for name in file-name-[0-9][0-9]*.txt
do
if [ -f "$name" ];
then
date=${name%%.txt}
date=${date/file-name-}
date=${date//-/}2359
with_tempfile $name
with_stat $name
fi
done