在没有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}'