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"
An you want the to become:
"system.20090101.log"
"something.20090101.log"
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
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
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)'
You will see a little report of what has been matched:
Let's see how the rename could be:
regex-rename '(\w+)-(\w+)-(\d+)-(\d+)-(\d+)-NODATA(\.txt)' '\1.\5\4\3\6'
The actual renaming:
regex-rename '(\w+)-(\w+)-(\d+)-(\d+)-(\d+)-NODATA(\.txt)' '\1.\5\4\3\6' --rename
Convert to lowercase or uppercase and adding leading zeros
Let's create a bunch of files for test
touch FILE-{1..10}.txt
Now run this command:
regex-rename '(\w+-)(\d+)(\.txt)' '\L\1\2\3' --pad-to=2 --rename
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.
Top comments (0)