Tuesday, February 8, 2011

Tokenize bash variables

Here is a useful set of bash features that I had to use today.

From the source linked above:

Given, foo=/tmp/my.dir/filename.tar.gz

We can use bash expressions to tokenize or extract different portions of the variable.

path = ${foo%/*} (/tmp/my.dir)
file = ${foo##*/} (filename.tar.gz)
base = ${file%%.*} (filename)
ext = ${file#*.} (tar.gz)

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

No comments:

Post a Comment