Naming file with first part of MIME type

Started by CrashCash, May 21, 2022, 01:27:40 AM

Previous topic - Next topic

CrashCash

I've written a bash script using exiftool to rename my files according to the creation date:

exiftool -d 'img-%Y-%m-%d_%H-%M-%S%%-2nc.%%e' '-filename<CreateDate' "$@"

This is great for images, but it also renames videos to img-blah-blah

I'd like to name it according to the first part of the MIME type:
if it's video/mp4 then I'd like it to be video-2021-08-12_17-37-32.mp4
if it's image/jpeg then I'd like it to be image-2021-08-12_17-37-32.jpg

I'm sure this is some quick Perl manipulation of the tag, but I've Googled and beat on it for a week, and not had any success. It doesn't help that I'm a Perl noob.

Can someone show me some sort of approach to this?


StarGeek

Try
exiftool -d '%Y-%m-%d_%H-%M-%S%%-2nc.%%e' '-Filename<${MIMEType;m/^([^\/]+)/;$_=$1}-$CreateDate' /path/to/files/

This takes the MIMEType, which will be in the format of image/jpeg or video/mp4, matches everything up to the slash, and replaces the value of the tag with the match.

A less complicated command would be to run two separate commands and use the -ext (-extension) option to limit the scope of files
exiftool -ext jpg -d 'img-%Y-%m-%d_%H-%M-%S%%-2nc.%%e' '-filename<CreateDate'
exiftool -ext mp4 -d 'vid-%Y-%m-%d_%H-%M-%S%%-2nc.%%e' '-filename<CreateDate'

Also of possible interest to you would be to use find and directly pass the results to exiftool. See this post for an example.
* Did you read FAQ #3 and use the command listed there?
* Please use the Code button for exiftool code/output.
 
* Please include your OS, Exiftool version, and type of file you're processing (MP4, JPG, etc).

CrashCash

Thanks, that worked! That regular expression is what was killing me. They always do. TBH, it took me half an hour to pick your RE apart and figure out what it was doing.

StarGeek

Check out Regex101.  You can get a step-by-step breakdown of an expression

For example, the regex from above.  You can mouse over the expression in the box or read the explanation in the upper right.
* Did you read FAQ #3 and use the command listed there?
* Please use the Code button for exiftool code/output.
 
* Please include your OS, Exiftool version, and type of file you're processing (MP4, JPG, etc).