How Can I Change File Dates Based on Their Names?

April 21, 2025 4 answers
Asked by draft~revision
I'm looking for a way to edit the created and modified dates of several files based on naming conventions. My files follow formats like .trashed-1737661897-video_20241213_152336.mp4, IMG-20190622-WA0006.jpg, and others. Right now, all their dates are set to today, and I want to update them according to the info in their filenames. Are there any tools or commands that can help me achieve this?

Answers

_63 drum lessons
If you want to go for a pure bash solution, you can try something like this: ``` for f in "${fnames[@]}"; do bf=${f##*/} if [[ $bf =~ .*[^0-9](20[0-9]{6})[^0-9]([0-9]{4})([0-9]{2})[^0-9].* ]]; then touch -t "${BASH_REMATCH[1]}${BASH_REMATCH[2]}.${BASH_REMATCH[3]}" "$f"; elif [[ $bf =~ .*[^0-9](1[0-9]{9})[0-9]{3}[^0-9].* ]]; then touch -t "$(date -d "@${BASH_REMATCH[1]}" +%Y%m%d%H%M.%S)" "$f"; else read -erp "Touch date for '$bf' (YYYYmmddHHMM.SS): "; [[ -n $REPLY ]] && touch -t "$REPLY" "$f"; fi; done ``` This checks for different date formats and can prompt you for dates if it doesn't recognize them!
Reply to this answer
~almost certain
It's important to note that when you move files between different filesystems, their 'created at' time might reset since it refers to when they were added to that filesystem. For media files, there are utilities that can pull dates from embedded EXIF data, which can be a game changer if you have a lot of images!
Reply to this answer
+72 survey replies
You might find it tricky since usually user-level tools canโ€™t change file creation times directly. It differs by filesystem as well, but on some systems, like FreeBSD, you might be able to set it back by using the modification time if itโ€™s earlier than the creation date. Not a solid solution, just something to keep in mind!
Reply to this answer
micronScale7
There's a command line approach you can try, which works for most of your filenames (except for the IMG-20190622-WA0006.jpg). Hereโ€™s a sample script you can use: ``` for file in * .*; do new_date=$(perl -ne 's/.*(dddd)(dd)(dd)_(dd)(dd)(dd).*/$1-$2-$3 $4:$5:$6/ and print' <<< "$file"); if [[ -n $new_date ]]; then touch -d "$new_date" "$file"; fi; done ``` This will help extract dates and apply them accordingly!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions