在外壳程序中仅过滤三个字符 [英] Filter only three characters in shell

查看:79
本文介绍了在外壳程序中仅过滤三个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在shell中解析命令,并且在一个选项中,如果字符串具有"r""w""x",其中之一,全部,我想保存到变量中,或混合,但只有这三个.不允许其他字符!

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!

我尝试了以下情况:

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

但是在这种情况下,如果写入了zr,它将通过,因为它具有"r".只要它具有这三个,三个或两个(任何一种组合)但没有其他字符,我只想让它通过.

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.

推荐答案

在BASH中,您可以使用正则表达式进行此检查,如下所示:

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

正则表达式^[rwx]+$允许1个或多个rwx字母.

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

这篇关于在外壳程序中仅过滤三个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆