coder007 coder007 - 1 month ago 7
Bash Question

rename files in a folder using find shell

i have a n files in a different folders like abc.mp3 acc.mp3 bbb.mp3 and i want to rename them 01-abc.mp3, 02-acc.mp3, 03-bbb.mp3... i tried this

#!/bin/bash

IFS='
'
COUNT=1
for file in ./uff/*;
do mv "$file" "${COUNT}-$file" let COUNT++ done


but i keep getting errors like for syntax error near 'do and sometimes for not found... Can someone provide single line solution to this using "find" from terminal. i'm looking for a solution using find only due to certain constraints... Thanks in advance

Answer

I'd probably use:

#!/bin/bash

cd ./uff || exit 1

COUNT=1 
for file in *.mp3;
do
    mv "$file" $(printf "%.2d-%s" ${COUNT} "$file")
    ((COUNT++))
done

This avoids a number of issues and also includes a 2-digit number for the first 9 files (the next 90 get 2-digit numbers anyway, and after that you get 3-digit numbers, etc).