Operating System - HP-UX
1829608 Members
1384 Online
109992 Solutions
New Discussion

korn shell: check string content of a variable and then do other steps

 
SOLVED
Go to solution
support_billa
Valued Contributor

korn shell: check string content of a variable and then do other steps

hello,

 

i have a string in a variable :

 

option 1:
ENTRY=";;DEF#<KEY1>#<KEY2>#RAW#junk#junk#junk#junk"

 option 2:

ENTRY=";;DEF#<KEY1>#<KEY2>#FS#junk#junk#junk#junk"

 

i want to check , if string has content "DEF#<KEY1>#<KEY2>" 

 

does a easier solution exists like:

if [ "$( echo "${ENTRY}" | sed -e "s|;;||g" -e "s|#[RF][AS][A-Z]*#junk#junk#junk#junk||g" )" = "DEF#<KEY1>#<KEY2>" ]
then
.
.

 

regards


2 REPLIES 2
Bill Hassell
Honored Contributor

Re: korn shell: check string content of a variable and then do other steps

Probably simpler code would be:

 

if [[ $(echo "$ENTRY" | grep -c "DEF#<KEY1>#<KEY2>") -ne 0 ]]
then...

 If the string is found, result is not equal to zero.



Bill Hassell, sysadmin
Dennis Handly
Acclaimed Contributor
Solution

Re: ksh: check string content of a variable and then do other steps (pattern)

>I want to check if string has content "DEF#<KEY1>#<KEY2>" 

>does a easier solution exists like:

 

Yes, a real shell can do it much easier:

#!/usr/bin/ksh
ENTRY=";;DEF#<KEY1>#<KEY2>#RAW#junk#junk#junk#junk"
if [[ ${ENTRY} = *DEF#\<KEY1\>#\<KEY2\>* ]]; then
   echo "$ENTRY matches pattern lit"
else
   echo "$ENTRY doesn't match pattern"
fi

ENTRY=";;DEF#<KEY1>#<KEY2>#FS#junk#junk#junk#junk"
if [[ ${ENTRY} = *DEF#\<KEY1\>#\<KEY2\>* ]]; then
   echo "$ENTRY matches pattern lit"
else
   echo "$ENTRY doesn't match pattern"
fi
# Use a variable
PATTERN="*DEF#<KEY1>#<KEY2>*"
if [[ ${ENTRY} = ${PATTERN} ]]; then
   echo "$ENTRY matches pattern variable"
else
   echo "$ENTRY doesn't match pattern"
fi

 

Since you have to do lot of quoting for the literal case, putting the pattern in a variable is much easier.

 

>if [[ $(echo "$ENTRY" | grep -c "DEF#<KEY1>#<KEY2>") -ne 0 ]]

 

You might want to simplify this to:

echo "$ENTRY" | grep -q "DEF#<KEY1>#<KEY2>"

if [ $? -eq 0 ]; then