linuxbashscriptingrenamesuffix

Bash Script rename file to modified day and add suffix


| Filename | DateModified | After Rename |
| --- | --- | --- |
| aaa.mp3 | 20230114 | 20230114_1.mp3 |
| bbb.mp3 | 20230113 | 20230113_1.mp3 |
| ccc.mp3 | 20230114 | 20230114_2.mp3 |
| ddd.mp3 | 20221205 | 20221205_1.mp3 |
| eee.mp3 | 20230113 | 20230113_2.mp3 |

I have a folder "/volume1/music/" with multiple random named mp3 file inside.

I want to rename file to date modified and add inscrease suffix to advoid same name.

I use the code below but don't know how to handle the counter suffix

cd "/volume1/music/"
counter=1
for file in *.mp3; do
    cdate=$(date -r "$file" +"%Y%m%d")
        echo "$cdate"
        if [ -f "$cdate" ]; then
            set counter=counter+1
        else 
            set counter=0
        fi
    echo mv "$file" "$cdate"_"$counter"
done

Thank you for your help!


Solution

  • Just move the counter initialisation inside the loop, and increment by repeatedly testing existence of full name rather than just date string.

    You can add a test to avoid renaming files that already have the correct name format.

    cd "/volume1/music/"
    
    for oldfile in *.mp3; do
        cdate=$(date -r "$oldfile" +"%Y%m%d")
        echo "$cdate"
    
        if [[ $oldfile =~ ^[0-9]{8}_[0-9]{1,}\.mp3$ ]]; then
            if [[ $oldfile =~ ^"$cdate" ]]; then
                echo "skipping $oldfile"
                continue
            fi
        fi
    
        counter=1
        while
            newfile="${cdate}_${counter}.mp3"
            [ -e "$newfile" ]
        do
            (( counter++ ))
        done
    
        echo mv "$oldfile" "$newfile"
    done