Bash Hackery

January 12th, 2011

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

 
Search for Posts
2014
 
2013
 
2012
 
2011
 
2010
 
 
© 2013 Andy Ferguson