How can I remove the text
[ MyBook ] from
[ MyBook ] Chapter 5.docx using the linux command line, for multiple files?
This was the question I wanted to answer, as I was too lazy to manually rename each file one by one.
Right, so step 1: take a backup.
There is nothing worse than fudging something like this up and ending up in a worse place than where you started.
A simple copy / paste to a new folder should suffice.
To remove the text
[ MyBook ] from the file names of multiple files using the command line in Linux, you can use the
rename command. The
rename command is a utility for renaming multiple files at once, and it can be used with a regular expression to match and replace specific patterns in the file names.
Here’s the basic syntax for using
rename with a regular expression to remove the text
[ MyBook ] from the file names:
This command will search for the pattern
\[ MyBook \] in the file names and replace it with an empty string (i.e., it will remove the text).
* at the end tells
rename to apply the changes to all files in the current directory.
Keep in mind that
rename is a very powerful command, and it can be dangerous to use it with regular expressions if you’re not careful.
Help With Regex
Half the battle with this approach is knowing what regular expression to use. All those escape characters are a pain in the ass.
Fortunately, online regex escape utilities do make this much easier than it once was.
Firstly, head over to Online RegEx Escape and enter your text as normal:
It is also then worth testing the validity of the generated regular expression on RegExr:
In the above I realised I had missed out a trailing space from my input at Online RegEx Escape.
All I did here was copy the full output from my original terminal window, paste it into the block on RegExr and use that to validate the reg ex pattern would match.
If all looks good, run the command:
Be sure to test the command on a small sample of files before running it on all of your files, and make sure you have a backup of your data just in case something goes horribly wrong.