3

Mac Os X does not have the useful linux command rename, which has the following format:

rename 'perl-regex' list-of-files

So here's what I have put together but it does not rename any files ($new is always the same as $file):

#!/usr/bin/env perl -w
use strict;
use File::Copy 'move';

my $regex=shift;
my @files=@ARGV;

for my $file (@files)
{
    my $new=$file;
    $new =~ "$regex";    # this is were the problem is !!!
    if ($new ne $file) 
    {
        print STDOUT "$file --> $new \n";
        move $file, ${new} or warn "Could not rename $file to $new";
    }
}

It is as if I am not passing the regexp and if I hard code it to

$new =~ s/TMP/tmp;

it will work just fine... Any thoughts?

Reza Toghraee
  • 1,565
  • 1
  • 12
  • 21
  • possible duplicate of [How can I easily bulk rename files with Perl?](http://stackoverflow.com/questions/1836563/how-can-i-easily-bulk-rename-files-with-perl) – Andy Lester Feb 03 '13 at 20:09
  • **What does "doesn't work" mean?** "Doesn't work" is an inadequate description for us to understand the problem. What happened when you tried it? Did you get incorrect results? Did you get *no* results? If the results were incorrect, what made them incorrect? What were you expecting instead? Did you get *any* correct results? If so, what were they? Don't make us guess. – Andy Lester Feb 03 '13 at 20:09
  • 3
    *Mac Os X does not have the useful linux command `rename`* — More precisely, it doesn't come with it preinstalled. There's nothing stopping you [installing the File::Rename package](https://metacpan.org/module/File::Rename). (Note that the default name for the executable is `file-rename`, you can symlink or alias it to `rename` if you like). – Quentin Feb 03 '13 at 20:13
  • Take a look at [eval()](http://perldoc.perl.org/functions/eval.html). – m0skit0 Feb 03 '13 at 20:23

4 Answers4

3
$operator = 's/TMP/tmp/';
print $operator; 

doesn't magically evaluate the operator, so it should be no surprise that

$operator = 's/TMP/tmp/';
$x =~ $operator; 

doesn't either. If you want to evaluate Perl code, you're going to have to pass it to the Perl interpreter. You can access it using eval EXPR.

$operator = 's/TMP/tmp/';
eval('$x =~ '.$operator.'; 1')
   or die $@;
ikegami
  • 343,984
  • 15
  • 249
  • 495
2

You cannot put the whole sentence s/TMP/tmp; in a variable. You can, though, do something like

$new =~ s/$find/$replace;

$find being your regex and $replace what you want to replace the matches with.

If you still want to pass the whole sentence, you might want to take a look at eval().

m0skit0
  • 23,973
  • 11
  • 79
  • 120
  • you mean something like: my $regex = eval(shift); then it complains about use of uninitialized value $_ in substitution (s(///) at [the next line] – Reza Toghraee Feb 03 '13 at 20:30
  • I don't know what you mean about next line being s///. I don't see that line in your code. And *If you still want to pass the whole sentence, you might want to take a look at eval()* – m0skit0 Feb 03 '13 at 20:34
2

There are two ways this can be solved elegantly

  1. Require two seperate command line arguments: One for the regex, and one for the replacement. This is inelegant and restrictive.

    my ($search, $replace, @files) = @ARGV;
    
    ...;
    
    my $new = $file;
    $new =~ s/$search/$replace/e; # the /e evals the replacement,
                                  # allowing us to interpolate vars
    

    Invoked like my-rename '(.*)\.txt' '@{[our $i++]}-$1.foo' *.txt. This allows to execute almost any code⁽¹⁾ via string variable interpolation.

    (1): no nested regexes in older perls

  2. Just allow arbitrary Perl code, similar to perl -ne'...'. The semantics of the -n switch are that the current line is passed as $_. It would make sense to pass filenames as $_, and use the value of the last statement as the new filename. This would lead to something like

    # somewhat tested
    my ($eval_content, @files) = @ARGV;
    
    my $code = eval q' sub {
       no strict; # could be helpful ;-)
       my @_out_;
       FILENAME:
       for (@_) {
          my $_orig_ = $_;
          push @_out_, [ $_orig_ =>  do { ' . $eval_content . q' } ];
          # or
          #     do { " . $eval_content . " };
          #     push @_out_, [ $_orig_, $_ ];
          # if you want to use $_ as out-argument (like -p).
          # Can lead to more concise code.
       }
       return @_out_;
    } ';
    die "Eval error: $@" if $@;
    
    for my $rename ($code->(@files)) {
        my ($from, $to) = @$rename;
        ...
    }
    

    This could be invoked like my-rename 'next FILENAME if /^\./; our $i++; s/(.*)\.txt/$i-$1.foo/; $_' *.txt. That skips all files starting with a dot, registeres a global variable $i, and puts a number counting upwards from one in front of each filename, and changes the extension. Then we return $_ in the last statement.

    The loop builds pairs of the original and the new filename, which can be processed in the second loop.

    This is probably quite flexible, and not overly inefficient.

amon
  • 56,161
  • 2
  • 84
  • 146
2

Well, it is already a Perl utility, and it's on CPAN: http://cpan.me/rename. You can use the module which comes with that utility, File::Rename, in a direct way:

#!/usr/bin/env perl
use File::Rename qw(rename);
rename @ARGV, sub { s/TMP/tmp/ }, 'verbose';

Other possibility is to concatenate the module and the script from that distribution and put the resulting file somewhere into your $PATH.

creaktive
  • 5,155
  • 2
  • 17
  • 32