DEV Community

Cover image for The amazing python regex-rename package
Sérgio Araújo
Sérgio Araújo

Posted on • Updated on

The amazing python regex-rename package

Source:

The idea of this post comes from https://serverfault.com/questions/5685/ on serverfault.com, Renaming files in Linux with a regex

Let's say you have these files:

"System-Log-01-01-2009-NODATA.txt"
"Something-Log-01-01-2009-NODATA.txt"
Enter fullscreen mode Exit fullscreen mode

An you want the to become:

"system.20090101.log"
"something.20090101.log"
Enter fullscreen mode Exit fullscreen mode

I have been using perl-rename a lot, (it is on the util-linux) package or you can run:

cpan
cpan1> install File::Rename

sudo ln -s /usr/local/bin/rename /usr/bin/rename.pl
Enter fullscreen mode Exit fullscreen mode

But this time I stumbled upon regex-rename, and I felt the obligation to share this tool with all of you guys.

Let's first install it:

pip3 install --user regex-rename
Enter fullscreen mode Exit fullscreen mode

By default, it does not rename files, just shows you if your regex is matching any file:

regex-rename '(\w+)-(\w+)-(\d+)-(\d+)-(\d+)-NODATA(\.txt)'
Enter fullscreen mode Exit fullscreen mode

You will see a little report of what has been matched:

Alt Text

Let's see how the rename could be:

regex-rename '(\w+)-(\w+)-(\d+)-(\d+)-(\d+)-NODATA(\.txt)' '\1.\5\4\3\6'
Enter fullscreen mode Exit fullscreen mode

The actual renaming:

regex-rename '(\w+)-(\w+)-(\d+)-(\d+)-(\d+)-NODATA(\.txt)' '\1.\5\4\3\6' --rename
Enter fullscreen mode Exit fullscreen mode

Convert to lowercase or uppercase and adding leading zeros

Let's create a bunch of files for test

touch FILE-{1..10}.txt
Enter fullscreen mode Exit fullscreen mode

Now run this command:

regex-rename '(\w+-)(\d+)(\.txt)' '\L\1\2\3' --pad-to=2 --rename
Enter fullscreen mode Exit fullscreen mode

The \L before group 1 says regex-rename to convert the group to lowercase and the option --pad-to=2 adds leading zeros to the file names.

Discussion (0)