Reputation: 383
I am looking for a way in Bash to rename my file prefixes. These files are all in one folder. No other files will be in it.
00 - Artist - Title.mp3
01 - Artist - Title.mp3
... and so on
to
01 - Artist - Title.mp3
02 - Artist - Title.mp3
... and so on
The prefix can also be only a single (0, 1, 2, ...), double(00, 01, 02, ...), triple, ... prefixes.
Upvotes: 1
Views: 54
Reputation: 48023
It's risky business, but it here's a sh solution that seems to work:
ls *.mp3 | sort -rn | while read f
do
number=`echo "$f" | sed 's/ .*//'`
rest=`echo "$f" | sed 's/^[^ ]* //'`
number2=`expr $number + 1`
number2f=`printf %02d $number2`
mv -i "$number $rest" "$number2f $rest"
done
sort -rn
so that it won't try to overwrite anything if there are adjacently-numbered files with the same artist and title (which probably won't happen, although it does if I take your example literally).
mv -i
so it will ask you before it overwrites anything if there are any of those cases that manage to come up anyway.
If you have a cleaner way you like to break things like $f
up into $number
and $rest
, be my guest.
Upvotes: 0
Reputation: 242123
Perl solution:
perl -we 'for (@ARGV) {
my ($n, $r) = /^([0-9]+)(.*)/;
rename $_, sprintf("%0" . length($n) . "d", 1 + $n) . $r;
}' *.mp3
The regular expression match extracts the number to $n and the rest to $r. $n + 1 is then formatted by sprintf to be zero padded, having the same length as the original number.
Note that it changes the length of the number for 9, 99, etc.
Upvotes: 1