Operating System - HP-UX
1819791 Members
3300 Online
109607 Solutions
New Discussion юеВ

Pattern matching for variables within a korn shell program

 
SOLVED
Go to solution
Mr Peter Kempner
Occasional Contributor

Pattern matching for variables within a korn shell program

All I want to do is use regular expression type
pattern match testing in a korn shell script to test a variable.

Put another way,
Is pattern matching only available for use on lines in a file (with utils like sed, grep awk etc) or can I use it on a variable in a script file?
4 REPLIES 4
Robin Wakefield
Honored Contributor
Solution

Re: Pattern matching for variables within a korn shell program

Hi Peter,

Just echo the variable through a pipe, e.g.

# VAR=hello
# echo $VAR | grep "el"
hello
# echo $VAR | sed 's/e/u/'
hullo
# echo $VAR | awk '{print substr($0,2,3)}'
ell

Rgds, Robin
John Palmer
Honored Contributor

Re: Pattern matching for variables within a korn shell program

Hi,

Extended pattern matching is available in the shell for if and case statements etc.

Excerpt from 'man sh-posix':-

In addition to the notation described in regexp(5), sh recognizes composite patterns made up of one or more pattern lists separated from
each other with a |. Composite patterns can be formed with one or more of the following:

?(pattern-list) Matches any one of the given patterns.
*(pattern-list) Matches zero or more occurrences of the given
patterns.
+(pattern-list) Matches one or more occurrences of the given
patterns.
@(pattern-list) Matches exactly one of the given patterns.
!(pattern-list) Matches anything, except one of the given
patterns.

Regards,
John
John Palmer
Honored Contributor

Re: Pattern matching for variables within a korn shell program

I should also have mentioned that it's much more efficient to use the shell's built in features rather than having to fork a new process (like grep).

For instance:
VAR=hello
echo $VAR|grep "el"

could be done internally with:
if [[ ${VAR} = *el* ]];
then...

or using an example of the shell extensions:
if [[ ${VAR} = *(?)el*(?) ]];

Regards,
John
Peter Kloetgen
Esteemed Contributor

Re: Pattern matching for variables within a korn shell program

Hi Peter,

you have also a second way to set a value to a variable: ( this is called command substitution )

var=`pwd` # these are back- ticks, this syntax will be understood by all shells, even the Bourne- shell accepts it

var=$(pwd) # this syntax can be used for ksh and POSIX shell

# pwd
/home/peter

# var=`pwd`

# echo $var | grep 'peter'
/home/peter
#

Allways stay on the bright side of life!

Peter
I'm learning here as well as helping