Home > database >  Bash Script rename file to modified day and add suffix
Bash Script rename file to modified day and add suffix

Time:01-14

| 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!

CodePudding user response:

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

CodePudding user response:

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

Something like this:

#!/usr/bin/env bash

cd /volume1/music/ || exit

shopt -s nullglob extglob

for file in ./!([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-9]*).mp3; do
  counter=1
  ext="${file##*.}"
  cdate=$(date -r "$file"  "%Y%m%d") || exit
  echo "$cdate"
  if [[ -n "$cdate" ]]; then
    while [[ -e "$cdate"_"$counter"."$ext" ]]; do
      ((counter  ))
    done
    echo mv -vn "$file" "$cdate"_"$counter"."$ext" || exit
  fi
done

  • Remove the echo if you think the output is ok.
  • Related