Coder Perfect

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

Problem

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

"stackoverflow"

the final outcome should be

"13"

Asked by lacrosse1991

Solution #1

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

https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

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
    13

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

${#str_var}  

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 https://stackoverflow.com/questions/15596199/how-can-i-count-the-number-of-characters-in-a-bash-variable