How Can I Change File Dates Based on Their Names?

0
0
Asked By CuriousCoder92 On

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?

4 Answers

Answered By BashBuster On

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!

Answered By TechSavvyTom On

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!

Answered By DataDude42 On

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!

Answered By ScriptedSam On

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!

Related Questions

Convert Json To Xml

Bitrate Converter

GUID Generator

GUID Validator

Convert Json To C# Class

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.