'How to rename files by creation date in OSX?
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 1:[1]
Complete Example
The solution by Amadan was very helpful and of course correct. Maybe like me, others are searching for the finished example. I figured it out and it looks like this:
one-liner:
for f in *.jpg; do D=$(date -r $(stat -f %B $f) +%Y-%m-%d-%H-%M-%S); mv "$f" "$D-$f"; done
readable version:
for file in *.jpg
do VARIABLE_DATE_OF_FILE=$(date -r $(stat -f %B $file) +%Y-%m-%d-%H-%M-%S)
mv "$file" "$VARIABLE_DATE_OF_FILE-$file"
done
Solution 2:[2]
You don't need date on macOS to get your desired format. Just do this:
stat -f %SB -t "%y-%m-%d" FILE
The %S tells stat to format the following data item (here B) as a string and the -t option tells stat how dates are formatted as strings.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Phlow |
| Solution 2 | Mecki |
