Thursday, July 30, 2009

Matching and replacing substrings using Bash

The Bash shell has some pretty nifty tricks when it somes to substring matching and replacement. The documentation over at TLD is very comprehensive but here's the gist of it:
${string#substring}
Deletes shortest match of $substring from front of $string.

${string##substring}
Deletes longest match of $substring from front of $string.

${string%substring}
Deletes shortest match of $substring from back of $string.

${string%%substring}
Deletes longest match of $substring from back of $string.
So to provide an example when working with filenames, given the following files:
file123.txt
file456.txt
file789.txt
If I want to rename them all to be Document-123.txt, Document-456.txt etc. I could do the following:
for f in file*; do 
mv $f Document-${f#file}
done
And to rename the extensions to .doc, it's as easy as:
for f in Document-*; do
mv $f ${f%.txt}.doc
done
A more practical example might be to convert all FLAC files in a directory to MP3s and rename the extensions along the way. To achieve this you'd need flac and lame installed and do something like:
for f in *.flac; do 
flac -cd "$f" | lame -h - "${f%.flac}.mp3"
done
Easy!

0 comments:

Post a Comment