Jan 11

filenames …

Tag: Bashberrisch @ 7:39 pm

The whole article …..

Here's where a few examples would have helped.
To understand the man page I simply experimented
with the echo command and several shell variables.
This is what it all means:
      Given:
            foo=/tmp/my.dir/filename.tar.gz 

      We can use these expressions:

      path = ${foo%/*}
          To get: /tmp/my.dir (like dirname)
      file = ${foo##*/}
          To get: filename.tar.gz (like basename)
      base = ${file%%.*}
          To get: filename
      ext = ${file#*.}
          To get: tar.gz 

      Note that the last two depend on the assignment made in the second one

Here we notice two different "operators" being used inside the parameters (curly braces).
Those are the # and the % operators.
We also see them used as single characters and in pairs.
This gives us four combinations for trimming patterns off the beginning or end of a string:

${variable%pattern}
    Trim the shortest match from the end
${variable##pattern}
    Trim the longest match from the beginning
${variable%%pattern}
    Trim the longest match from the end
${variable#pattern}
    Trim the shortest match from the beginning

Leave a Reply