Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Rename files with $EDITOR

by bumby (Beadle)
on Jul 30, 2010 at 13:00 UTC ( [id://852079]=CUFP: print w/replies, xml ) Need Help??

A handy script for moving (renaming) files.
#!/usr/bin/perl =head1 Author: Martin (bumby) Stenberg Name: emv Description: Rename files using $EDITOR Start date: 2010-07-30 Last updated Date: 2010-07-30 =cut use File::Temp qw/tmpnam tempfile/; use File::Basename; use File::Copy; use Data::Dumper; use Getopt::Std; use Env qw/EDITOR/; use strict; my $help = <<EOF; Usage: emv [OPTION] FILES Rename FILES using \$EDITOR ($EDITOR). -h Display this help message -p Pretend to rename files, don't actually do it The script handles overwriting name changes such as "a -> b; b -> a" w +hich means you can swap two filenames by swapping their line positions: a.txt b.txt to b.txt a.txt EOF my %opts; getopts( 'hp', \%opts ); die $help if $opts{h}; chomp(@ARGV = <STDIN>) unless @ARGV; # write file names to temporary file my ($fh, $file) = tmpnam() or die "Error: Could not create temporary f +ile: $!\n"; print $fh $_,"\n" for @ARGV; close($fh); # open file name list in $EDITOR system($EDITOR, $file); # read in new file names open(FILE, $file) or die "Error: Could not open temporary file: $!\n"; my @NEWNAMES = (); chomp(@NEWNAMES = <FILE>); close(FILE); unlink($file); die "Erro: File names does not align. Please do not add or remove line +s while renaming files in $EDITOR.\n" if $#ARGV != $#NEWNAMES; my %files = (); for(my $i=0; $i < @NEWNAMES; $i++) { $files{$ARGV[$i]} = $NEWNAMES[$i]; } foreach my $fname (keys %files) { next if $fname eq $files{$fname}; # skip unchanged names # handle overwriting name changes, e.g: a -> b; b -> a if(exists $files{$files{$fname}}) { my (undef, $tmpfile) = tempfile(DIR => dirname($files{$fname}) + ,OPEN => 0); mv($files{$fname}, $tmpfile); mv($fname, $files{$fname}); mv($tmpfile, $fname); delete $files{$files{$fname}}; } else { mv($fname, $files{$fname}) if $fname and exists $files{$fname} +; } } sub mv { my ($from, $to) = @_; if($opts{p}) { print "$from -> $to", "\n"; }else { move($from, $to); } }

Replies are listed 'Best First'.
Re: Rename files with $EDITOR
by hossman (Prior) on Jul 31, 2010 at 05:02 UTC

    The idea behind this script both terrifies, and excites me.

    The script itself however frightens me, because there are some edge cases that can have some relaly nasty behavior...

    • There's a risk of some silent catastrophic user error if a person inadvertently attempts to rename two different files to the same file (ie: "a->x and b->x" ... or if they mean to do "a->b and b->a" but they forget to change one and wind up with a->b and b->b). It would be pretty easy to prevent this type of error by doing an "exists" around line #60
    • There's a really bad assumption in your "handle overwriting name changes" ... it will work for a->b and b->a but not any other generalized overlaps like "a->b and b->c". This is because the loop over the keys only checks for the existence of the "target" file as a key in the hash and if it exists it creates a temp file -- but it never looks at the value that "target" had in the hash when moving the tmpfile, it just assumes you wanted a straight swap.
    • Even if you fix the previous bug by using mv($tmpfile, $files{$files{$fname}}); instead of mv($tmpfile, $fname); I still think it's possible you're going to wind up edge cases where things fail depending on what files get processed in -- in particular consider the case of "a->b and b->c and c->a"

    I think the only safe way to deal with all of this is that if you detect your $target is already a key in the hash, you need to mv($target,$tmpfile) and then update the hash, ala: $files{$tmpfile} = $files{$target}; delete $files{$target};. It complicates things because you can't do a simple loop over a one time copy of the keys, but that's not a big deal. Just do a "while (keys %files) { $fname = (keys %files)[0]; ...; delete $files{$fname}; }" type flow instead.

      Yeah, I was going to point out some of those same problems.

      I wrote the same basic tool about 20 years ago. Since then it has been one of my most heavily-used tools.

      It was usually the first tool I missed when I moved to a new environment. And I've been surprised over the years to not run into this functionality by other authors.

      I remember missing my precious mvi and thinking, "Oh, vim lets you edit directories, I'll just use that". Gah, what an awkward interface. I can't even do :%s/HTM/html/. I can't use all of the vi features to get all of the file names just right.

      So it was nice to finally see this simple idea cross my path. (Surely others have written such a tool, just not that I've run into.)

      Over the years my mvi has grown. It is now over 500 lines, actually. It handles all of the cases you outlined. It also lets you copy, link, or delete files. Deleting files leads to the case of "delete b; mv a b" which would be ugly if you did those steps in the wrong order. It deals with very badly named files. It lets you pick whether you want to overwrite files and/or be asked first (it was always important that it be a safe way to rename files -- in fact, I'd often reach for it to do a very simple rename because I knew it wouldn't overwrite even when I didn't have a local equivalent for "mv -n" or wasn't sure what the local equivalent of "mv -i" was).

      I'll post the code for it in a bit.

      bumby++

      Update: Posted at mvi -- mv+vi (+ln+rm+cp+mkdir).

      - tye        

        Thanks for the feedback and mvi, very useful tool!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://852079]
Approved by Corion
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2024-04-19 19:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found