7

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
  • 151
  • 2
  • 8

3 Answers3

5

But how do I count the characters including spaces?

To count length of string use:

echo "${#sentence}"
47
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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,199
  • 1
  • 15
  • 35
0

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

echo "this string" | grep -oP . | grep -c .
Maroun
  • 94,125
  • 30
  • 188
  • 241