Issue
I'm looking to create a solution to rename files by the creation date yy-mm-dd
and not the actual date for Mac and Ubuntu. I already know how to create an app with AppleScript and call it hourly with launchd
and Ubuntu use a CRON job when files are sent to the repo for storage that do not have the creation date at the beginning of the file.
I can rename files by today's date with:
for file in *.zip; do
mv -n "$file" "$(date +%Y%m%d_"$file")"
done
but when I try:
for f in *.zip; do
D=$(stat -n '%Y%m%d' $f)
mv -v "$f" "$D_$f"
done
nothing happens. I am able to use stat foobar.zip
to get the date of the file but is there a way I can do this for the creation date so when I write my conditional to test if a date doesn't exist to apply the creation date? I somewhat recall being able to do date -r
in Ubuntu but that isn't available on Mac. I've searched on SO, AskUbuntu and Unix but I am unable to find a solution that would allow me the option to do this. I thought about testing with stat
and awk
to set as the variable D
and rename it that way.
Solution
D=$(date -r $(stat -f %B $f) +%Y%m%d)
$(...)
will execute a command and insert the output into the command line. We do this twice: first stat -f %B $f
executes, with $f
substituted with the current file; -f %B
means "gimme inode birth time as UNIX timestamp". This will produce something like 1440737362
as output; next, this value is inserted into the next layer, and date -r 1440737362 +%Y%m%d
is executed. This will convert the UNIX timestamp into the YYmmdd format: 20150828
. This is again inserted into the next outer layer, and we get D=20150828
, which assigns the human-readable-ish ctime to the variable D
.
EDIT: changed %c
(inode change time) to %B
(inode birth time)
Answered By - Amadan Answer Checked By - Candace Johnson (WPSolving Volunteer)