Magellan Magellan - 1 year ago 68
Bash Question

Scrip Shell to change name of all my files but with specifics rules

I have a car and my audio post only read music with a specific order.

I have a big list of music, and I want to change every justanexemple.mp3 on 001|justanexemple.mp3 and the next one "i love stackoverflow.mp3" on "002|i love stackoverflow"

Also, we get one limit is when I'm on the 009|music.mp3, and I want the next one like this 010|music.mp3

I also get a problem is I have some music with space like this "I like turtles.mp3"
so the command mv doesn’t function...

So I coded something like this



for file in `ls -1 *.mp3 | sort -t. -k 2n`
if [ $file != $newname ]
then mv $file $newname
counter=`expr $counter + 1`
echo $counter done

but is not working great...

my music list is something like that :

> Kario & Yaret - Somos Lokos (Prod. By Las Ovejas Negras & Gaby.mp3
> Dj_Foxx-T_-_An_Sé_an_Nonm_(feat._Pompis)_-_.mp3
> Harry_Toddler_-_Draw_Mi_Table_wegotitfirst_com.mp3 Kario & Yaret Ft.mp3
> Mc Cassidy Ft. Polakan Y Delirious - Bad Boy.mp3


Answer Source
  1. Don't parse ls
  2. Don't use string concatenation to format numbers. Use printf
  3. Quote your variables

Your script can be written as:

for i in *.mp3; do
  pref=$(printf "%03d" $c)
  echo "$i" "${pref}|$i"

If the output seems good, replace echo with mv to perform the actual rename.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download