Shell Script: Different Method to Find Out Number of Characters in a String

To count total number of characters in a string
Count total number of
$ mystring="This is my test string"
$ echo "${#mystring}"
22
$ expr length "$mystring"
22

$ echo $mystring|awk '{print length}'
22
$ len=`echo $mystring | wc -c`;echo `expr $len - 1`
22

To count specific characters in sting.
$ grep -o "[s|S]" <<<"$mystring" | wc -l
4
$ grep -o "[ ]" <<<"$mystring" | wc -l
4
$ grep -o "[T|i]" <<<"$mystring" | wc -l
4
$ grep -o "[s|i]" <<<"$mystring" | wc -l

7

No comments:

Post a Comment