Linux 如何计算 Bash 变量中的字符数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15596199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I count the number of characters in a Bash variable
提问by lacrosse1991
How can I count all characters in a bash variable? For instance, if I had
如何计算 bash 变量中的所有字符?例如,如果我有
"stackoverflow"
the result should be
结果应该是
"13"
采纳答案by SteveP
Using the ${#VAR}
syntax will calculate the number of characters in a variable.
使用${#VAR}
语法将计算变量中的字符数。
https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
回答by aga
${#str_var}
where str_var
is your string.
str_var
你的字符串在哪里。
回答by Raj
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
回答by mihai
Use the wcutility with the print the byte counts(-c
) option:
使用带有打印字节数( ) 选项的wc实用程序:-c
$ 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.
您必须使用不输出尾随换行符( -n
) 选项echo
。否则,换行符也将被计算在内。
回答by Norbert Wupona
you can use wc to count the number of characters in the file wc -m filename.txt. Hope that help.
您可以使用 wc 来计算文件 wc -m filename.txt 中的字符数。希望有所帮助。