Search code examples
bashshellglobfile-renameangular2-cli

Rename all files with the name pattern *.[a-z0-9].bundle.*, to replace the [a-z0-9] with a given string


On building apps with the Angular 2 CLI, I get outputs which are named, for instance:

inline.d41d8cd.bundle.js
main.6d2e2e89.bundle.js

etc.

What I'm looking to do is create a bash script to rename the files, replacing the digits between the first two . with some given generic string. Tried a few things, including sed, but I couldn't get them to work. Can anyone suggest a bash script to get this working?


Solution

  • A pure-bash option:

    shopt -s extglob    # so *(...) will work
    generic_string="foo"   # or whatever else you want between the dots
    for f in *.bundle.js ; do
        mv -vi "$f" "${f/.*([^.])./.${generic_string}.}"
    done
    

    The key is the replacement ${f/.*([^.]./.${generic_string}.}. The pattern /.*([^.])./ matches the first occurrence of .<some text>., where <some text> does not include a dot ([^.]) (see the man page). The replacement .${generic_string}. replaces that with whatever generic string you want. Other than that, double-quote in case you have spaces, and there you are!

    Edit Thanks to F. Hauri - added -vi to mv. -v = show what is being renamed; -i = prompt before overwrite (man page).