6

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?

vikiv
  • 141
  • 2
  • 8

3 Answers3

5

But how do I count the characters including spaces?

To count length of string use:

echo "${#sentence}"
47
anubhava
  • 713,503
  • 59
  • 514
  • 593
0

You can also use grep with a regex that matches everything:

echo "this string" | grep -oP . | grep -c .
Maroun
  • 91,013
  • 29
  • 181
  • 233
0

Using awk on a single line:

echo this string | awk '{print length}'

Another way of piping stdin text to awk:

awk '{print length}' <<< "this string"
Yaron
  • 1,165
  • 1
  • 14
  • 33