Thursday, October 22, 2009

Variable modifiers in csh and bash: bash

Bash do not have variable modifiers, but it has a feature called Posix, which originates from ksh and seems to be more powerful, albeit somewhat more cryptic.

% is used to remove smallest suffix pattern. Like:
$ gatesfile=/home/gates/bin/foo.bar
$ echo ${gatesfile%.bar}
/home/gates/bin/foo
Of course you can append something to the end and forge the functionality of replace:
$ echo ${gatesfile%.bar}.x
/home/gates/bin/foo.x
%% is to remove largest suffix pattern:
$ gatesfile=posix/src/std
$ echo ${gatesfile%%/*}
posix
# is used to remove smallest prefix pattern, and ## is to remove largest prefix pattern

In summary, given:
a=/a/b/c/d
b=b.xxx

+------------------------------------+
|csh bash result |
+------------------------------------+
|$a:h ${a%/*} /a/b/c |
|$a:t ${a##*/} d |
|$b:r ${b%.*} b |
|$b:e ${b##*.} xxx |
+------------------------------------+

No comments: