I have three files named
file1.txt
file2.txt
file3.txt
I am trying to rename them to
mynewfile-1.txt
mynewfile-2.txt
mynewfile-3.txt
How would I go about this using regular expressions?
Like this :
rename -n 's/^file/mynewfile-/' ./*.txt
or from comments :
rename -n 's/^file(\d+)/mynewfile-${1}-test/' ./*.txt
___ ____
^ ^
capturing group |
captured group
Drop -n
switch when the output looks good to rename for real.
There are other tools with the same name which may or may not be able to do this, so be careful.
The rename command that is part of the util-linux
package, won't.
If you run the following command (GNU
)
$ rename
and you see perlexpr
, then this seems to be the right tool.
If not, to make it the default (usually already the case) on Debian
and derivative like Ubuntu
:
$ sudo apt install rename
$ sudo update-alternatives --set rename /usr/bin/file-rename
For archlinux:
pacman -S perl-rename
For RedHat-family distros:
yum install prename
The 'prename' package is in the EPEL repository.
For Gentoo:
emerge dev-perl/rename
For *BSD:
pkg install p5-File-Rename
For Mac users:
brew install rename
If you don't have this command with another distro, search your package manager to install it or do it manually
Or you can use perl CPAN:
cpan -i File::Rename
Old standalone version can be found here
This tool was originally written by Larry Wall, the Perl's dad.