Rename multiples files using Bash scripting

  • I want to rename multiple files in the same directory using Bash scripting. Names of the files are as follows:

    file2602201409853.p
    file0901201437404.p  
    file0901201438761.p  
    file1003201410069.p  
    file2602201410180.p
    

    I want to rename to the following format:

    file2503201409853.p
    file2503201437404.p  
    file2503201438761.p  
    file2503201410069.p  
    file2503201410180.p
    

    I was reading about the rename command, and try to do it this way, but it does nothing, I think I have questions about the syntax. Then I read that you can make a loop using the mv command as follows:

    for file in cmpsms*2014*.p; do
        mv "$file" "${file/cmpsms*2014*.p/cmpsms25032014*.p}"
    done
    

    But I can not rename the files. What am I doing wrong?

    You can't have a pattern expression on the right hand side of a parameter expansion replacement expression. What did you expect to be where that `*` is?

    @Kiwy That question is about removing a portion of the file name. Ergo, highly doubtfully duplicate.

    Next time, please describe the file name changes you want to make (I had to look at this for a fair while before seeing the differences and similarities). Examples are good, but a description *as well as* examples is even better.

  • Oli

    Oli Correct answer

    7 years ago

    You were right to consider rename first. The syntax is a little strange if you're not used to regexes but it's by far the quickest/shortest route once you know what you're doing:

    rename 's/\d{4}/2503/' file*
    

    That simply matches the first 4 numbers and swaps them for the ones you specified.

    And a test harness (-vn means be verbose but don't do anything) using your filenames:

    $ rename 's/\d{4}/2503/' file* -vn
    file0901201437404.p renamed as file2503201437404.p
    file0901201438761.p renamed as file2503201438761.p
    file1003201410069.p renamed as file2503201410069.p
    file2602201409853.p renamed as file2503201409853.p
    file2602201410180.p renamed as file2503201410180.p
    

    Note that this is the Perl rename on Debian and derivatives (Ubuntu, Mint, …). On other Linux distributions, `rename` is a completely different file renaming tool (which Debian ships as `rename.ul`).

    If your distributive lack of such tool, look at @Michael Campbell answer. I think every distributive replace default `rename` like debian did.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM