简体   繁体   中英

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).

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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