hi there,
i'm using OS X.
i have a bunch of mp3 files strewn across a directory tree that i'd like to rename.
specifically i'd like to remove any track numbers and leading non-alphabetic characters from the filenames like this:
01 - song1.mp3
2 song2.mp3
become:
song1.mp3
song2.mp3
this accomplishes what i want within a given directory:
for i in [0-9];do mv "$i" "`echo $i|sed 's/^[0-9]*[^a-zA-Z]//'`";done
any idea on how i can do this easily through an entire directory tree?
i tried to write a simple script using find to output each directory name, cd into it, and run the above command. the problem is that many directory and file names have special characters like spaces, parentheses, commas, ampersands, apostrophes, etc.
is there an easy way to deal with this?
thanks in advance
find ./ -iname '[0-9]*.mp3' | while read FILE
do
echo "Working on file $FILE"
done
thanks for the quick reply.
that helps me in spitting out the path/file names, but then using sed to get rid of the leading characters is beyond my abilities.
the output looks like:
./path/to/file/01 - song.mp3
...
how can i then rename it to song.mp3 (leaving it in the original directory)? it's not as obvious to me anymore since "01 - " isn't at the start of the string.
thanks again
---------- Post updated at 04:49 PM ---------- Previous update was at 04:46 PM ----------
and also there could be numbers/non-alphabetic characters in the pathname that i'd like to leave intact
IFS="/" # Split on /
find ./ -name '[0-9]*.mp3' | while read FILE
do
set -- $FILE # Split ./path/whatever.mp3 into $1=., $2=path, $3=whatever.mp3
P="$1"
shift
while [ "$#" -gt 1 ] # Build up the contents of P into ./path/
do
P="$P/$1"
shift # Delete current $1, set $1=$2, $2=$3, ...
done
# Should be left with the path in P, and the file itself in $1
echo "File is $1"
echo "Path is $P"
NEWNAME="whatever.mp3"
echo mv "$P/$1" "$P/$NEWNAME"
done
that's great. thanks so much.
here's the final version i'm using just for the record:
#!/bin/sh
IFS="/" # Split on /
find ./ -name '[0-9]*.mp3' | while read FILE
do
P=""
set -- $FILE
while [ "$#" -gt 1 ]
do
[ -z "$P" ] || P="${P}/"
P="$P$1"
shift
done
echo "old name is $1"
NEWNAME=$(echo $1 | sed 's/^[0-9]*[^a-zA-Z]*//')
echo "new name is $NEWNAME"
mv "$P/$1" "$P/$NEWNAME"
done
Note that if you have two tracks on an album in iTunes that have the same song name (and something like "English version" and "Spanish version" in comments instead of as a parenthetical element in the song title), you could end up overwriting all but one of the tracks. To play it safe, I'd check to be sure that $P/$NEWNAME doesn't exist before doing the move.
1 Like
thanks much. makes sense. i changed it to mv -i to avoid that.
another small hiccup i came across: in my ~15k song library, i had one filename that was only numbers and got renamed to mp3