I have a variable set like this:
sentence="a very long sentence with multiple spaces"
I need to count how many words and characters are there without using other programs such as wc.
I know counting words can be done like this:
words=( $sentence )
echo ${#words[@]}
But how do I count the characters including spaces?
Words could be counted with sed 's/[[:space:]]/\n/g' filename | grep -c .
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
Using the ${#VAR} syntax will calculate the number of characters in a variable. Link could die. ${#parameter} gives the length in characters of the expanded value of parameter is substituted. If parameter is * or @ , the value substituted is the number of positional parameters.
But how do I count the characters including spaces?
To count length of string use:
echo "${#sentence}"
47
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With