This feature offered by the shell with regards to its variables, comes in quite handy. I highlight a portion of this feature with which one can extract and use only a part of a string contained in a shell variable. The string gets truncated from either the left or the right end. The following command transcript should be self-explanatory.
$ VAR="[begin]:A_left_furthest:A_middle:A_right_furthest:[end]"
$ echo ${VAR#*A}
_left_furthest:A_middle:A_right_furthest:[end]
$ echo ${VAR##*A}
_right_furthest:[end]
$ echo ${VAR%A*}
[begin]:A_left_furthest:A_middle:
$ echo ${VAR%%A*}
[begin]:
The # or ## markers enable truncation from the left side; while the % and %% markers performs truncation from the right side of the string.
One situation in which I often find myself using variable substitution is when I need to convert a list of WAV files that were ripped from my CD, to MP3 or FLAC files.
Assuming I'm in the directory with a bunch of WAV files (with .wav extension in filename) and wish to convert them to MP3, I could do something like this:
for FILE in `ls *.wav`
do
lame -b 256 $FILE $(FILE%\.wav).mp3
doneNote:
- I converted all *.wav files in the current directory, to MP3 format, with the resulting files' .wav extension replaced by a .mp3 extension. A constant bit-rate of 256 kbps was selected for the mp3 encoding property.
- Lame was used for the audio file format conversion.