Search code examples
bashfile-rename

changing the name of many files by increasing the number


I want to change the file names from a terminal. I have many files, so I cannot change all of them one by one.

a20170606_1257.txt -> a20170606_1300.txt
a20170606_1258.txt -> a20170606_1301.txt

I am only able to change it by:

rename 57.txt 00.txt *57.txt

but it is not enough.


Solution

  • Just playing with parameter expansion to extract the longest and shortest strings of type ${str##*} and ${str%%*}

    offset=43
    for file in *.txt; do 
        [ -f "$file" ] || continue
        woe="${file%%.*}"; ext="${file##*.}"
        num="${woe##*_}"
        echo "$file" "${woe%%_*}_$((num+offset)).${ext}"
    done
    

    Once you have it working, remove the echo line and replace it with mv -v. Change the offset variable as you wish, depending on where you want to start your re-named files from.