[Gllug] Swapping two parts of a filename...

Russell Howe rhowe at wiss.co.uk
Mon Jun 7 00:43:17 UTC 2004


On Wed, Jun 02, 2004 at 10:59:19PM +0100, Dylan wrote:
> Hi All,
> 
> I have a bunch of mp3's with filenames like:
> 
> Track Name - Artist Name.mp3
> 
> which I'd really rather like as
> 
> Artist Name - Track Name.mp3
> 
> Is there an easy way to accomplish this? I also need to handle cases 
> where the track name or artist name contains a hyphen (in which case, 
> it would have a non-space character on each side.)

If you save this as a shell script...

#!/bin/bash
# Might work in plain ol' sh too

for FILEPATH in "$@"; do
	DIR="$(dirname "$FILEPATH")"
	FILE="$(basename "$FILEPATH")"
	BASE="${FILE%.mp3}"
	[ "$FILE" = "${BASE}.mp3" -a "$BASE" != "${BASE/ - /}" ] && mv -iv "${DIR}/$FILE" "${DIR}/${BASE/* - /} - ${BASE/ - */}.mp3"
done

# End of file


Save it as, e.g. foo.sh, make it executable (chmod +x foo.sh) and feed
in the list of files to process as command line parameters:

find /path/of/sillynamed/files -name '*.mp3' -type f -print0|xargs -0 foo.sh

Not quite a one-liner, and it'll be pretty slow (4 fork()'s per file or
so), but shows off some common shell scripting constructs.

Maybe someone more familiar with shell programming could do it without
having to save the logic off into a seperate file...

If you are to try this, a useful trick is to add the word 'echo' before
the 'mv'. This will echo the commands to stdout instead of executing
them, allowing you to check it's not about to do Bad Things(tm) to your
files. See the mv manpage for the -i and -v options

-- 
Russell Howe     | Why be just another cog in the machine,
rhowe at wiss.co.uk | when you can be the spanner in the works?
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list