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,603
  • 1
  • 14
  • 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

5 Answers5

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
  • 367,544
  • 15
  • 269
  • 518
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
  • 25,268
  • 11
  • 79
  • 127
  • 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
  • 57,091
  • 2
  • 89
  • 149
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,193
  • 2
  • 18
  • 32
0

Better download the real script with no dependencies:

wget https://raw.githubusercontent.com/sputnick-dev/perl-rename/master/rename
#!/usr/bin/perl -w
#
#  This script was developed by Robin Barker (Robin.Barker@npl.co.uk),
#  from Larry Wall's original script eg/rename from the perl source.
#
#  This script is free software; you can redistribute it and/or modify it
#  under the same terms as Perl itself.
#
# Larry(?)'s RCS header:
#  RCSfile: rename,v   Revision: 4.1   Date: 92/08/07 17:20:30 
#
# $RCSfile: rename,v $$Revision: 1.5 $$Date: 1998/12/18 16:16:31 $
#
# $Log: rename,v $
# Revision 1.5  1998/12/18 16:16:31  rmb1
# moved to perl/source
# changed man documentation to POD
#
# Revision 1.4  1997/02/27  17:19:26  rmb1
# corrected usage string
#
# Revision 1.3  1997/02/27  16:39:07  rmb1
# added -v
#
# Revision 1.2  1997/02/27  16:15:40  rmb1
# *** empty log message ***
#
# Revision 1.1  1997/02/27  15:48:51  rmb1
# Initial revision
#

use strict;

use Getopt::Long;
Getopt::Long::Configure('bundling');

my ($verbose, $no_act, $force, $op);

die "Usage: rename [-v] [-n] [-f] perlexpr [filenames]\n"
    unless GetOptions(
    'v|verbose' => \$verbose,
    'n|no-act'  => \$no_act,
    'f|force'   => \$force,
    ) and $op = shift;

$verbose++ if $no_act;

if (!@ARGV) {
    print "reading filenames from STDIN\n" if $verbose;
    @ARGV = <STDIN>;
    chop(@ARGV);
}

for (@ARGV) {
    my $was = $_;
    eval $op;
    die $@ if $@;
    next if $was eq $_; # ignore quietly
    if (-e $_ and !$force)
    {
    warn  "$was not renamed: $_ already exists\n";
    }
    elsif ($no_act or rename $was, $_)
    {
    print "$was renamed as $_\n" if $verbose;
    }
    else
    {
    warn  "Can't rename $was $_: $!\n";
    }
}

__END__

=head1 NAME

rename - renames multiple files

=head1 SYNOPSIS

B<rename> S<[ B<-v> ]> S<[ B<-n> ]> S<[ B<-f> ]> I<perlexpr> S<[ I<files> ]>

=head1 DESCRIPTION

C<rename>
renames the filenames supplied according to the rule specified as the
first argument.
The I<perlexpr> 
argument is a Perl expression which is expected to modify the C<$_>
string in Perl for at least some of the filenames specified.
If a given filename is not modified by the expression, it will not be
renamed.
If no filenames are given on the command line, filenames will be read
via standard input.

For example, to rename all files matching C<*.bak> to strip the extension,
you might say

    rename 's/\.bak$//' *.bak

To translate uppercase names to lower, you'd use

    rename 'y/A-Z/a-z/' *

=head1 OPTIONS

=over 8

=item B<-v>, B<--verbose>

Verbose: print names of files successfully renamed.

=item B<-n>, B<--no-act>

No Action: show what files would have been renamed.

=item B<-f>, B<--force>

Force: overwrite existing files.

=back

=head1 ENVIRONMENT

No environment variables are used.

=head1 AUTHOR

Larry Wall

=head1 SEE ALSO

mv(1), perl(1)

=head1 DIAGNOSTICS

If you give an invalid Perl expression you'll get a syntax error.

=head1 BUGS

The original C<rename> did not check for the existence of target filenames,
so had to be used with care.  I hope I've fixed that (Robin Barker).

=cut
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223