Find string in variable

korn shell,

testing if a pattern exist in a string,
x is constant, y could be none,all or any combination of the elements of x,

x="aa bb cc dd ee ff gg hh ii jj kk ll"
y="ff kk"
for z in `echo ${x}`
do
 if [ <any pattern in $y matches any pattern in $x> ]
   then
     do something
 fi
done

Try:

for z in $x
do
  case $y in
    *$z*) echo "a pattern in \$y matches any pattern in \$x"; break
  esac
done
1 Like

Recent ksh s (as well as bash es) provide a regex match in conditional expressions. man ksh:

So your code could read:

x="aa bb cc dd ee ff gg hh ii jj kk ll"
y="ff kk"
$ for z in $x; do [[ "$y" =~ "$z" ]] && echo $z; done
ff
kk

Aside: that `echo ${x}` is pointless - get rid of it.

1 Like

If 'pattern' stands for 'word' and 'match' for 'is equal to', then nested loops seem most correct.

for x1 in $x; do
 for y1 in $y; do
  if [ "$x1" = "$y1" ]; then
   echo "$x1"
  fi
 done
done
1 Like