Renaming files in multiple folders in Linux

One of the reasons I like Linux is that it makes batch editing of files much easier. Where once I would have had to write a Python script to edit multiple files, now I can (after much Googling) write a simple(ish) command in the terminal to do the same. One example is renaming files.

For some work I'm doing, I realised that I'd given a parameter a name that was different from previously, which resulted in thousands of text files with the incorrect name. Which seemed like a good opportunity to learn how to use the Linux rename command.

As described here, the command, which is actually a Perl file works like this:

> rename oldname newname files_to_change

Or

> rename regex files_to_change

My problem was made slightly more complex by the fact that the files were in different folders. The command I ran was:

> rename 's/(\d+)\/d+_name1/$1\/$1_name2' */*_name1

The */*_name1 tells the command to only consider files that are in any subfolder but have a filename ending in "_name1". The regex tells the script to substitute the name of any file in a folder with a integer name (\d+)\/ and a filename with is a sequence of digits followed by _name1 d+_name1 with the same folder and same starting digit, followed by _name2 $1\/$1_name2. In this case the digits for the folder name and the same of the filename were the same.

A very useful flag is -n, which shows you which files will be renamed and to what without actually changing anything, so you can make sure your regex works as you expect it to.

Topics:

Comments

I suggest to try KrojamSoft BatchRenameFiles program. It’s really work for me.

Post new comment

The content of this field is kept private and will not be shown publicly.