In ksh, you can do complicated pattern matching using
conditional expressions, which look a little like test
statements but are vastly superior.
In a test statement, the "[" acts as a synonym for test with
one change, it requires a closing "]". It is treated as a
command, just as if you had written "test" or "/bin/test".
Command line expansion occurs with all attendant perils.
In a conditional expression, consisting of a statement bracketted
by "[[" and "]]", the "[[" and "]]" elements are keywords, just like
"case" and "esac". And, just as you never need to quote the tested
variable in a case statement you never need to quote the left hand
side of a conditional expression:
case $var in pattern) ;; pattern) ;; esac
works for all values of $var.
case "$var" in pattern) ;; pattern) ;; esac
is never necessary. Similarly:
[[ $var = whatever ]]
and
[[ -f $var ]]
work for all values of $var.
In addition, filename substitution is no performed in a
conditional expression (well, except for one release of ksh
put out by HP-UX (;-)). The globbing characters are used to match
patterns:
abc=abc
if [[ $abc = b* ]];then ...
or
if [[ $abc = ?b* ]];then ...
In addition, there is an extended pattern notation. For instance:
if [[ $abc = !(def|ghi) ]]
will be true for all values of $abc that do not match "def" or
"ghi". You can easily construct very complicated match
expressions and do things that are impossible for regular
expressions. Ksh93 provides an additional mechanism using the
builtin "printf" command to generate extended pattern notation from
regular expressions:
$ re=$(printf "%P\n" "(abc|def)")
$ echo $re
*@(abc|def)*
$ for i in abc def ghi 1abc2 2def cabc
> do
> print -n "$i: "
> if [[ $i == $re ]];then print yes;else print no;fi
> done
abc: yes
def: yes
ghi: no
1abc2: yes
2def: yes
cabc: yes
$ re=$(printf "%P\n" "^(abc|def)")
$ echo $re
$ for i in abc def ghi 1abc2 2def cabc
> do
> print -n "$i: "
> if [[ $i == $re ]];then print yes;else print no;fi
> done
@(abc|def)*
abc: yes
def: yes
ghi: no
1abc2: no
2def: no
cabc: no
(ksh93 supports "==" for testing equality).
--
Dan Mercer
damer...@mmm.com
In article <3AE827AD.2AD64...@noaa.gov>,
Opinions expressed herein are my own and may not represent those of my employer.