我试图给自己写一些方便的脚本,以便合法地放弃工作更有效率,这个问题突然出现了:
给定一个非常长的字符串$LONGEST_EVER_STRING
和几个关键字字符串,如$A='foo bar'
,$B='omg bbq'
和$C='stack overflow'
如何在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
我知道我可以这样写,但看起来真的很难看:
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
有没有人有一个优雅的解决方案?非常感谢!
答案 0 :(得分:3)
您可以使用函数在A,B,C变量中进行一点变换,然后:
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
答案 1 :(得分:0)
我只想为此定义一个函数。对于大型单词列表,它会比grep慢,但比多次启动grep要快。
##
# Success if the first arg is one of the later args.
has() {
[[ $1 = $2 ]] || {
[[ $3 ]] && has "$1" "${@:3}"
}
}
$ has a b c && echo t || echo f
f
$ has a b c a d e f && echo t || echo f
t
答案 2 :(得分:0)
/ 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