Coder Perfect

I’m trying to figure out how to count the number of characters in a Bash variable. [duplicate]


What’s the best way to count all the characters in a bash variable? For example, if I had


the final outcome should be


Asked by lacrosse1991

Solution #1

The amount of characters in a variable can be calculated using the $#VAR syntax.

Answered by SteveP

Solution #2

Use the wc utility with the -c option to print the byte counts:

$ SO="stackoverflow"
$ echo -n "$SO" | wc -c

For echo, you’ll need to use the -n (do not output the trailing newline) option. If not, the newline character will be tallied as well.

Answered by mihai

Solution #3

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Counting the number of characters in a sentence, the number of words, the length of the words, and the total length of the sentence

Answered by Raj

Solution #4


where str var is the string you want to use.

Answered by aga

Solution #5

wc -m filename.txt can be used to count the number of characters in a file. I hope this information was useful.

Answered by Norbert Wupona

Post is based on