Friday, 19 August 2011

Bash trim filename

However, buried in there is a section on Parameter Substitution which tells us that $foo is really a shorthand for ${foo} which is really the simplest case of several ${foo:operators} and similar constructs.

    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

    ${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

No comments:

Post a Comment