Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting words and characters in Bash without wc [duplicate]

Tags:

bash

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?

like image 744
vikiv Avatar asked Oct 13 '15 08:10

vikiv


People also ask

How do you count words in a string without wc in Linux?

Words could be counted with sed 's/[[:space:]]/\n/g' filename | grep -c .

What does [- Z $1 mean in bash?

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

How do I count characters in a string in bash?

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.


1 Answers

But how do I count the characters including spaces?

To count length of string use:

echo "${#sentence}"
47
like image 66
anubhava Avatar answered Sep 19 '22 23:09

anubhava