Posted By

noah on 05/21/07


Tagged

regex Bash commandline name files utility rename tools


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

icecreamboyy


rename - Larry Wall's filename fixer


 / Published in: Perl
 

Invoke this script without any arguments to see the help text. From the Perl Cookbook, Ch. 9.9.

  1. #!/usr/bin/perl
  2. # -w switch is off bc HERE docs cause erroneous messages to be displayed under Cygwin
  3. #From the Perl Cookbook, Ch. 9.9
  4. # rename - Larry's filename fixer
  5. $help = <<EOF;
  6. Usage: rename expr [files]
  7.  
  8. This script's first argument is Perl code that alters the filename (stored in \$_ ) to reflect how you want the file renamed. It can do this because it uses an eval to do the hard work. It also skips rename calls when the filename is untouched. This lets you simply use wildcards like rename EXPR * instead of making long lists of filenames.
  9.  
  10. Here are five examples of calling the rename program from your shell:
  11.  
  12. % rename 's/\.orig$//' *.orig
  13. % rename 'tr/A-Z/a-z/ unless /^Make/' *
  14. % rename '$_ .= ".bad"' *.f
  15. % rename 'print "$_: "; s/foo/bar/ if <STDIN> =~ /^y/i' *
  16. % find /tmp -name '*~' -print | rename 's/^(.+)~$/.#$1/'
  17.  
  18. The first shell command removes a trailing ".orig" from each filename.
  19.  
  20. The second converts uppercase to lowercase. Because a translation is used rather than the lc function, this conversion won't be locale-aware. To fix that, you'd have to write:
  21.  
  22. % rename 'use locale; $_ = lc($_) unless /^Make/' *
  23.  
  24. The third appends ".bad" to each Fortran file ending in ".f", something a lot of us have wanted to do for a long time.
  25.  
  26. The fourth prompts the user for the change. Each file's name is printed to standard output and a response is read from standard input. If the user types something starting with a "y" or "Y", any "foo" in the filename is changed to "bar".
  27.  
  28. The fifth uses find to locate files in /tmp that end with a tilde. It renames these so that instead of ending with a tilde, they start with a dot and a pound sign. In effect, this switches between two common conventions for backup files
  29. EOF
  30.  
  31. $op = shift or die $help;
  32. chomp(@ARGV = <STDIN>) unless @ARGV;
  33. for (@ARGV) {
  34. $was = $_;
  35. eval $op;
  36. die $@ if $@;
  37. rename($was,$_) unless $was eq $_;
  38. }

Report this snippet  

You need to login to post a comment.