Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在没有wc的Bash中计算单词和字符_Bash - Fatal编程技术网

在没有wc的Bash中计算单词和字符

在没有wc的Bash中计算单词和字符,bash,Bash,我有这样一个变量集: sentence="a very long sentence with multiple spaces" words=( $sentence ) echo ${#words[@]} 我需要计算有多少字和字符,而不使用其他程序,如wc 我知道数词可以这样做: sentence="a very long sentence with multiple spaces" words=( $sentence ) echo ${#words[@]} 但是如

我有这样一个变量集:

sentence="a very long sentence with multiple       spaces"
words=( $sentence )
echo ${#words[@]}
我需要计算有多少字和字符,而不使用其他程序,如wc

我知道数词可以这样做:

sentence="a very long sentence with multiple       spaces"
words=( $sentence )
echo ${#words[@]}
但是如何计算包括空格在内的字符数呢

但是如何计算包括空格在内的字符数呢

要计算字符串的长度,请使用:

echo "${#sentence}"
47

您还可以将
grep
与匹配所有内容的正则表达式一起使用:

echo "this string" | grep -oP . | grep -c .

在单行上使用
awk

echo this string | awk '{print length}'
将标准文本输送到awk的另一种方式:

awk '{print length}' <<< "this string"
awk'{print length}'