Search code examples
linuxsystem-administration

Renaming lots of files in Linux according to a pattern


I'm trying to do three things with the mv command, but not sure it's possible? Probably need a script. not sure how to write it. All files are in same folder.

1) Files ending with v9.zip should just be .zip (the v9 removed)

2) Files containing _ should be -

3) Files with Uppercase letter next to a lowercase letter (or lowercase next to an Uppercase) should have a space between them. So MoveOverNow would be Move Over Now and ruNaway would be ruN away [A-Z][a-z] or [a-z][A-Z] becomes [A-Z] [a-z] and [a-z] [A-Z]


Solution

  • My favorite solution is my own rename script. The simplest example that maps to your problems are these:

    % rename 's/_/-/g' *
    % rename 's/(\p{Lower})(\p{Upper})/$1 $2/g' *
    

    Although I really hate whitespace in my filenames, especially vertical whitespace:

     % rename 's/\s//g' *
     % rename 's/\v//g' *
    

    et cetera. It’s based on a script by The Larry Wall, but extended with options, as in:

    usage: /home/tchrist/scripts/rename [-ifqI0vnml] [-F file] perlexpr [files]
        -i          ask about clobbering existent files
        -f          force clobbers without inquiring
        -q          quietly skip clobbers without inquiring
        -I          ask about all changes
        -0          read null-terminated filenames
        -v          verbosely says what its doing 
        -V          verbosely says what its doing but with newlines between old and new filenames
        -n          don't really do it
        -m          to always rename
        -l          to always symlink
        -F path     read filelist to change from magic path(s)
    

    As you see, it can change not just the names of files, but where symbolic links are pointing to using the same pattern. You don’t have to use a s/// pattern, although often one does.

    The other tools in that directory are mostly for Unicode work, of which there are some super-useful ones.