Sunday, February 26, 2023

bash: Variable substitutions

In bash, when I'm writing a for loop, I often need to specify an output file name with a different extension as the input file name. Bash has built-in variable substitutions which can do this. Here are a few that I use all the time:

  1. To change the file extension on a file name stored in a variable, use ${var%%search}replace.

    For example, to remove .wav from the end of a string and replace it with .mp3

    $ i=sound.wav
    $ echo ${i%%.wav}.mp3
    sound.mp3
  2. Get the equivalent of dirname from a variable. This discards everything after the last slash.

    $ i=/usr/bin/python3
    $ echo ${i%/*}
    /usr/bin
  3. Get the equivalent of basename from a variable. This discards everything before the last slash.

    $ i=/usr/bin/python3
    $ echo ${i##*/}
    python3

Using these substitutions is a lot faster than invoking a subprocess (i.e., $(dirname $i) or $(basename $i))