简体   繁体   English

如何从字符串中获取单个字符数或数字?

[英]How do I get individual number of characters, digits from a string?

How would i get the individual number of digits, characters and non-alpha numeric characters from a string? 我如何从字符串中获取单个数字,字符和非字母数字字符?

For example, the string "abc99@" would have (3 letters, 2 digits and 1 non alpha numeric character). 例如,字符串“ abc99 @”应具有(3个字母,2个数字和1个非字母数字字符)。

At the moment i have the following code but it gets the total characters where as i want individual. 目前,我有以下代码,但它得到了我想要的单个字符的总字符数。 How would i do this. 我该怎么做。

read input
echo ${#input}

You do not need additional tools: 您不需要其他工具:

letters="${input//[^a-zA-Z]}"; echo "${letters}: ${#letters}"
digits="${input//[^0-9]}"; echo "${digits}: ${#digits}"
other="${input//[0-9a-zA-Z]}"; echo "${other}: ${#other}"

Using grep -o and wc -l : 使用grep -owc -l

s="abc99."

# number of digits
grep -o '[0-9]' <<< "$s" | wc -l
2

# number of alphabets
grep -o '[a-zA-Z]' <<< "$s" | wc -l
3

# number of non-alphanumerics
grep -o '[^0-9a-zA-Z]' <<< "$s" | wc -l
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM