Renaming Files with PCRE via the Command Line

There exists a handy rename program for Linux, it differs slightly via distribution but the FreeBSD version is fueled by Perl and with it you get access to the PCRE engine. It’s pretty slick stuff and I will give a tutorial later on it.

Sometimes however, you may find yourself without this program or with the incorrect version that doesn’t have the Perly goodness under the hood. If you find yourself in this situation and want to rename files with the power of Perl’s regular expressions behind it you can always create your own. Luckily Perl is normally more readily available on many flavors of *nix distributions and systems.

In this example utilizing the power of a Perl one liner you can craft a solution as seen below:

perl -MFile::Copy -sle 'while (glob '*') { $o = $_; eval $r; unless ($o eq $_) { print qq~$o >>> $_~; move $o, $_ } }' -- -r='s`FIND`REPLACE`'

Bash Function

To make this more versatile and easy to invoke you can place it in your .bashrc configuration as seen below:

function rn 
{
	# $1 = replacement pattern in format of s`FIND`REPLACE`g
	# $2 = go makes it go otherwise preview

	perl -MFile::Copy -sle 'while (glob qq`*`) { $o = $_; eval $r; unless ($o eq $_) { print qq~$o >>> $_~; move $o, $_ if ($go eq q`go`) } }' -- -r=$1 -go=$2
} 

To invoke this on the command line you type the following:

  • rn 's~FIND~REPLACE~g' to run a trial test run
  • rn 's~FIND~REPLACE~g' go to instruct the program to proceed with the operation.

Running it without the go gives you insight on what exactly the program will do before doing it.

I hope you find this tutorial useful!

๐Ÿ‘ Get Blog Updates

๐Ÿ“ Latest Posts

0Shares
0

Leave a Reply