Sunday, December 21, 2008

Simple Shell/Bash RAR Renaming Script

Recently I ran into an issue using Mac OS X and RAR files. Using BetterZip I can use RAR files if they are a single file or spilt using the .rar, .r00, .r01, etc naming convention. I happened to get hold of an archive that was named .001, .002, etc.

So here's my soution to the problem. This will rename .002 onwards to .r00, leaving you to rename .001 to .rar. I could have added that but couldn't be arsed as it's a two second job to do a manual rename on a single file. 46 other files would have taken quite a bit longer.

#!/bin/sh

for i in `ls -a *.0*`
do
EXTENSION="$(echo ${i#*.})"
FNAME="$(echo ${i%.*})"
NEWNUM="$(echo $EXTENSION |sed 's/^0*//')"
NEWNUM="$(($NEWNUM -2))"
FINAME=""
if [ "$NEWNUM" -lt "10" ]; then
FINAME="$(echo $FINAME)0";
fi
FINAME="$(echo $FINAME$NEWNUM)"
FINAME="$(echo ${FNAME}.r$FINAME)"
echo "${i} -> ${FINAME}"
mv "$i" "$FINAME"
done
Probably not the most efficient script, but it works so there :)