阅读背景:

shell 脚本实现 限定输入内容

来源:互联网 
#!/bin/sh
# validAlphaNum - Ensures that input consists only of alphabetical
# and numeric characters.

validAlphaNum()
{
  # Validate arg: returns 0 if all upper+lower+digits, 1 otherwise

  # Remove all unacceptable chars
  compressed="$(echo 
#!/bin/sh
# validAlphaNum - Ensures that input consists only of alphabetical
# and numeric characters.

validAlphaNum()
{
  # Validate arg: returns 0 if all upper+lower+digits, 1 otherwise

  # Remove all unacceptable chars
  compressed="$(echo $1 | sed -e 's/[^[:alnum:]]//g')"

  if [ "$compressed" != "$input" ] ; then
    return 1
  else
    return 0
  fi
}

# Sample usage of this function in a script

echo -n "Enter input: "
read input

if ! validAlphaNum "$input" ; then
  echo "Your input must consist of only letters and numbers." >&2
  exit 1
else
  echo "Input is valid."
fi

exit 0


 

其中 sed -e 's/[^[:alnum:]]//g'  是过滤除数字和字母以外的内容

 

if [ "$compressed" != "$input" ] ; then 此处是给函数传参数input 的值

 

附:

过滤只留大写字母  空格 逗号 句号         

sed 's/[^[:upper:] ,.]//g'
过滤只留数字 圆括号 空格 -
sed 's/[^[:digit:]\(\) -]//g'
过滤只留数字
 
 
sed 's/[^[:digit:]]//g'

 

 


| sed -e 's/[^[:alnum:]]//g')" if [ "$compressed" != "$input" ] ; then return 1 else return 0 fi } # Sample usage of this function in a script echo -n "Enter input: " read input if ! validAlphaNum "$input" ; then echo "Your input must consist of only letters and numbers." >&2 exit 1 else echo "Input is valid." fi exit 0 #!/bin/sh # validAlphaNum - Ensures that input



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: