Filter only three characters in shell

╄→гoц情女王★ 提交于 2019-12-11 06:08:14

问题


I am trying to parse a command in shell, and in one of the options I want to save in a variable if a string has "r", "w", "x", one of those, all of them, or a mix, but only these three. No other characters should be allowed!

I tried a case where:

 $2 in *r*) ;; *w*) ;; *x*) ;; *  ) echo no ;;
esac

But in this case if there is written zr it will pass, as it has an "r". I only want to make it pass as long as it has one of these three, the three of them, or two of them (any kind of combination), but no other characters.


回答1:


In BASH you can use regex for this check like this:

re='^[rwx]+$'

s='rw'
[[ $s =~ $re ]] && echo "yes" || echo "no"
yes

s='zr'
[[ $s =~ $re ]] && echo "yes" || echo "no"
no

Regex ^[rwx]+$ will allow 1 or more of r or w or x letters.




回答2:


With extended pattern matching in Bash (shopt -s extglob):

if [[ $var == +([rwx]) ]]; then
    echo "Matches!"
else
    echo "Does not match!"
fi

The +([rwx]) pattern is "one or more of r, w or x".



来源:https://stackoverflow.com/questions/41557871/filter-only-three-characters-in-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!