How should exact keyword matching be used as a condition in a case expression?

I tried to write some useful scripts to legally cancel the work more efficiently, and this question suddenly appeared:

Given the very long line $LONGEST_EVER_STRING and a few lines with keywords like $A='foo bar' , $B='omg bbq' and $C='stack overflow'

How should exact keyword matching be used as a condition in a case ?

 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 this way, but it looks very 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? Thank you very much!

+6
source share
3 answers

You can use the function to do a little conversion in your variables A, B, C, 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 
+3
source

I would just define a function for this. This will be slower than grep for large word lists, but faster than running grep many times.

 ## # Success if the first arg is one of the later args. has() { [[ $1 = $2 ]] || { [[ $3 ]] && has "$1" "${@:3}" } } $ has abc && echo t || echo f f $ has abcadef && echo t || echo f t 
0
source

Option on / etc / bashrc "pathmunge"

 for word in $LONGEST_EVER_STRING; do found_word=false for list in " $A " " $B " " $C "; do if [[ $list == *" $word "* ]]; then found_word=true stuff with $list and $word break fi done $found_word || stuff when not found done 
0
source

All Articles