Friday, January 14, 2022

Remove that annoying part of the filename!

First Example:

This will match your pattern in the filename, and is great for movie files. In the first case case I am locating the whole filename up to the "s" or "S" indicating the the season of the title (upper and lower case), and the first and second digit ranging from 1-9 in the next two positions. Then I am locating the "e" or "E" indicating the episode portion of the filename, again upper and lower case instances, then finally the last two numbers indicating the episode count. I then match everything after the episode count for removal, rename the file, but keep the extension.

Copy and paste the following into your Bash Terminal:
find /home/USER/Movies -type f -iname '*mp4' -execdir rename 's/(.*)([sS][0-9][0-9][eE][0-9][0-9])(.*)/\2.mp4/g' '{}' ';'
------------------------------------------------------------------------------------------------------------------------------

Second Example:

Copy and paste the following into your Bash Terminal:
find /home/USER/Movies -type f -iname '*mp4' -execdir rename 's/(.*)(ENTER_PATTERN_TO REMOVE_HERE)(.*)/\2.mp4/g' '{}' ';'

Synopsis:

The "find" command is started looking for the data type "file", and anything with "mp4" in the filename in the users "Movies" folder. Then the "rename" shell is started inside find. We then make things more complicated by adding a command called "sed" to start the pattern match for us piped into the rename shell. It looks like this: 's///g'. The "/s" starts sed, the second "/" divides the "find and replace" fields, or 's/find/replace/g', and the "/g" switch allows "global" filename changes rather than only matching the first instance. This means if there are parts of the filename which have the same pattern they all will be changed in the string. Groups are defined by the parentheses: opened with "(" and closed with ")". I created three groups as you can see above. Group 1 is "(.*)" matching all characters before the pattern. The second group is the pattern to be removed, and group three is everything after your pattern except the filename extension. Group 2 is removed from the filename in all places throughout the filename string, then the filename extension is preserved, and the find command continues to locate more files under this folder for this processs.

Remember to make a backup of your primary library, execute this command, and enjoy your newly renamed files! No need to worry about sub-folders. Just run the command as is, and it will look in all folders under your primary folder. If you have a problem, just comment below and I will respond:)

**NOTE: Be CAREFULL to change the both parts of the line that refer to the filename extention to match! If you are looking for .mp3 files there are two places you need to change the reference from "*mp4" to "*mp3" and again from "\2.mp4" to "\2.mp3".