如何计算 Bash 变量中的字符数

如何计算 bash 变量中的所有字符? 例如,如果我有

"stackoverflow"

结果应该是

"13"
200058 次浏览
${#str_var}

where str_var is your string.

Using the ${#VAR} syntax will calculate the number of characters in a variable.

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

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

link Couting characters, words, lenght of the words and total lenght in a sentence

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

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

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

you can use wc to count the number of characters in the file wc -m filename.txt. Hope that help.