Technobabble
Grokking Technology

Bash Hackery

This is a cunning one I discovered today thanks to someone called vino. If you are a bash geek, you will already know this and, no doubt, use it every day; sadly I don’t hack on bash that often.

Problem

Strip-off an extension from a filename in a bash script

Solution

First time I solved this, I used sed, which is fine and so full of potential its a shame not to over-complicate it. Today I found this really neat hack

for FILE in *
  do
    if [ -f $FILE ]
    then
      # name without extension
      NAME=${FILE%.*}
      echo "Filename is ${NAME}"
    fi
  done

much more light-weight; the important bit being:

NAME=${FILE%.*}

I might even be able to remember this one!

Consulting my Bash reference states that

${var%pattern}

gives the value of var after removing pattern from the right


Page created on Sun 25 Apr 2021 by Andy Ferguson
Tag list: bash devel