Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use exact keyword matching as a condition in the case statement?

Tags:

regex

bash

I was trying to write myself some handy scripts in order to legitimately slacking off work more efficiently, and this question suddenly popped up:

Given a very long string $LONGEST_EVER_STRING and several keywords strings like $A='foo bar' , $B='omg bbq' and $C='stack overflow'

How should I use exact keyword matching as a condition in the case statement?

for word in $LONGEST_EVER_STRING; do
  case $word in
    any exact match in $A) do something ;;
    any exact match in $B) do something ;;
    any exact match in $C) do something ;;
    *)  do something else;;
  esac
done

I know I can write in this way but it looks really ugly:

for word in $LONGEST_EVER_STRING; do
  if [[ -n $(echo $A | fgrep -w $word) ]]; then
    do something;
  elif [[ -n $(echo $B | fgrep -w $word) ]]; then
    do something;
  elif [[ -n $(echo $C | fgrep -w $word) ]]; then
    do something;
  else
    do something else;
  fi
done

Does anyone have an elegant solution? Many thanks!

like image 678
Vincent.Z.Zhang Avatar asked Jan 13 '14 18:01

Vincent.Z.Zhang


1 Answers

You could use a function to do a little transform in your A, B, C variables and then:

shopt -s extglob
Ax="+(foo|bar)"
Bx="+(omg|bbq)"
Cx="+(stack|overflow)"
for word in $LONGEST_EVER_STRING; do
  case $word in
    $Ax) do something ;;
    $Bx) do something ;;
    $Cx) do something ;;
    *)  do something else;;
  esac
done
like image 183
Raul Andres Avatar answered Oct 19 '22 08:10

Raul Andres