Using Perl-Rename For File Substitution
I tried to use sed to rename filenames but found it rather cumbersome. sed is great when used to edit the content of a file which you can find some examples I created here, but I found this handy program that can do the same but for filenames instead.
Installed on my Arch, BTW, system I already had the program called rename which is not the same as the one we need called perl-rename. To install it I just ran it using pacman -S perl-rename. From here I was then able to rename a whole ton of files that I had scraped from the internet, cough cough youtube, quite easily.
What I first did was download all the videos from a certain content creator which had tons of special characters named files that I didn’t want named that way. I first began by editing each one by hand and then remembered Thunar has a batch rename program. I first used this to remove the last 12 or 13 characters that was added to each video after pulling them via yt-dlp which ended in [1234567890abc].webm. That was the easy part.
The next remaining videos had characters from :, ?, !, (), [], and even emojis. This was going to take a lot longer by hand especially with there being 400+ to rename. Luckily I found perl-rename just in time.
Using it is quite similar to sed where you call the substitute parameter and tell it what you want to replace and with what. Here is an example of what I used, taken from Stack Overflow of course, and tweaked for my usage.
$ perl-rename 's/[ @\:\!\,\)\(]/-/g' *
This a long string that does multiple things at once but when broken down is quite simple. Let’s start at the beginning.
- ’s/ is the initialization of the flag for substitute.
- Everything within the […] is going to be looped until the end.
- Right after the [ is an empty space then the @ symbol. This means anything with a space is going to be substituted along with anything with @.
- Following the @ is the backslash symbol. I can’t show it here since markdown sees it as a folder identifier. The backslash symbol is used to separate symbols like : and ! and , and ) and (.
- The next symbol which is a forward-slash, at the end of: $ perl-rename ’s/[ @:!,)(]/’, is used to separate what is wanted to be changed with what it will be changed to.
- - is what we are going to be changing all the special characters we added to be substituted to.
- And finally to close /g’ which globally changes everything.
Finally after all of this the filenames went from mostly ugly names to better separated names that I can then manually weed out those with even weirder special characters or emojis.
Similarly to this program, another that I have found to work quite well but works in a vim-like fashion is vimv which can be found here via the creator’s Github page.