A couple of months ago I wrote about a solution to recursively rename multiple files on a Linux system. The problem with that solution was that the script needed to be saved as a file called rename
and then chmod 755
to make it executable.
Today, while writing a script for my ASAP application, I found a much easier one line solution which uses commonly installed command line tools:
$ for i in `find . -name "*.php5"` ; do mv -v $i ${i/.php/.php5/}; done
This chain of commands searches for all files containing .php5
and renames them to .php
. The most obvious limitation of this solution is that if a filename or directory contains .php5
, it will also be renamed. So if, for some wacky reason, you had a directory called /my.php5.files/
, that directory would be renamed to /my.php.files/
. Similarly, a file named my.php5.example.php
would be renamed to my.php.example.php
.
For my application, this one liner worked fine as I simply added a warning to the top of my script. If anyone knows how I can easily modify that command to ignore all directories (I didn't see anything in the find
command syntax that might help), I would greatly appreciate the information!
find * -type f -name ‘*.php5’ -print | while read file; do mv “${file}” “$(basename “${file}” .php5).php”; done
This only catches files ending in .php5, and properly renames files that have spaces in their path.
Share and enjoy!
That’s awesome! Thanks Leo!
I’ve learned so much bash scripting since I wrote that post. Reading your one liner makes a lot more sense!
Derived from an example at:
http://mamchenkov.net/wordpress/2005/09/26/recursively-renaming-files-in-linux/
Rename files with suffix ‘php’ to ‘php5’:
rename -v ‘sphpphp5’ `find -P . -iname “*.php”`
-You just gotta luuuv oneliners!
Sweet! Thanks Per! 🙂