Search code examples
bashfile-rename

How do I rename and overwrite part of file name in Bash at the same time?


I have multiple JS files in folder, for example, foo.js, this_is_foo.js, foo_is_function.js.

I want to append a number which is passed as parameter in front of extension ".js", such as foo.1.js, this_is_foo.1.js, foo_is_function.1.js

I write a script to append a number successfully the first time, but if I run the script twice, it does not overwrite the first number but append right after that.

Actual result: foo.js --> foo.1.js (1st run) --> foo.1.2.js (2nd run).

Expected result: foo.js --> foo.1.js (1st run) --> foo.2.js (2nd run).

This is my script:

#!/bin/sh
param=$1
for file in *.js; do
    ext="${file##*.}";
    filename="${file%.*}";
    mv "$file" "${filename}.${param}.${ext}";
done

How can I do that? I want to write pure bash script, not to use any tools.


Solution

  • Before doing the rename you can check if what is after the last dot in filename (${filename%.*}) is numeric. If so switch that with param instead of appending a new param

    Since you are writing that you want to use pure bash I assume that it is ok to change the shebang to #!/bin/bash:

    #!/bin/bash
    param=$1
    for file in *.js; do
        ext="${file##*.}";
        filename="${file%.*}";
    
        # Check if what is after the last dot in filename is numeric
        # Then assume that it should be switched to param
        if [[ ${filename##*.} =~ ^[0-9]+$ ]]; then
            mv "$file" "${filename%.*}.${param}.${ext}"
    
        ## Else add param
        else
            mv "$file" "${filename}.${param}.${ext}"
        fi  
    done
    

    Testrun

    $> touch a.js && find -type f -name *.js && \
     ./test.sh 1 && find -type f -name *.js && \
     ./test.sh 2 && find -type f -name *.js
    
    ./a.js
    ./a.1.js
    ./a.2.js