Replace string in file names, bash one-liner

After running lame on a bunch of wav files I ended up with tons of files named:


song1.wav.mp3
song2.wav.mp3
song3.wav.mp3
song4.wav.mp3
...

Now, obviously I could have avoided this in this case with the proper options and arguments to lame, but it’s all in hindsight.

Here’s the bash line I use to strip out .wav from the middle of all these files in the current directory:


for filename in *.mp3; do newname=`echo $filename | sed 's/\.wav\.mp3$/.mp3/g'`; mv $filename $newname; done

It’s long for one line but I think it’s still understandable and manageable. The result is:


song1.mp3
song2.mp3
song3.mp3
song4.mp3
...

Note: I notice that I’m being overly carefully with my regexes and wildcards in the example above but it should make it more clear how to adapt it to your case.

Tags: , , , , , , , , , , ,

2 Responses to “Replace string in file names, bash one-liner”

  1. DeeShell says:

    Hi,

    thanks for the great hint!
    Just a question: why do we need to use the $ symbol just after mp3? What if I avoid to use it? It seems it’s something about “length” of the two strings…

    Thanks for answer.

    Danilo

  2. ajx says:

    The $ means that it should match .wav.mp3 only at the end of the file name. So a file called foo.wav.mp3.bar.zip would not be matched.

Leave a Reply