我如何知道bash变量(空格分隔的标记)中的标记数量 - 或者至少,它是一个还是更多。
答案 0 :(得分:30)
我无法理解为什么人们一直在使用那些过于复杂的基础知识。几乎总是一个直接的,无基础的解决方案。
howmany() { echo $#; }
myvar="I am your var"
howmany $myvar
这使用内置于shell的tokenizer,因此没有差异。
这是一个相关的问题:
myvar='*'
echo $myvar
echo "$myvar"
set -f
echo $myvar
echo "$myvar"
请注意,使用bash数组的@guns解决方案具有相同的问题。
以下是一个(据称)超级健壮的版本来解决问题:
howmany() ( set -f; set -- $1; echo $# )
如果我们想避免使用子shell,事情开始变得丑陋
howmany() {
case $- in *f*) set -- $1;; *) set -f; set -- $1; set +f;; esac
echo $#
}
这两个必须与引号一起使用,例如howmany "one two three"
返回3
答案 1 :(得分:29)
$#扩展将告诉你变量/数组中的元素数量。如果你正在使用大于2.05左右的bash版本,你可以:
VAR='some string with words'
VAR=( $VAR )
echo ${#VAR[@]}
这有效地将字符串沿着空格(默认分隔符)拆分为数组,然后计算数组的成员。
编辑:
当然,这会将变量重组为数组。如果您不想这样,请使用其他变量名称或将变量重新转换为字符串:
VAR="${VAR[*]}"
答案 2 :(得分:9)
set VAR='hello world'
echo $VAR | wc -w
这是你可以检查的方式。
if [ `echo $VAR | wc -w` -gt 1 ]
then
echo "Hello"
fi
答案 3 :(得分:1)
要算:
sentence="This is a sentence, please count the words in me."
words="${sentence//[^\ ]} "
echo ${#words}
检查:
sentence1="Two words"
sentence2="One"
[[ "$sentence1" =~ [\ ] ]] && echo "sentence1 has more than one word"
[[ "$sentence2" =~ [\ ] ]] && echo "sentence2 has more than one word"
答案 4 :(得分:0)
答案 5 :(得分:0)
简单方法:
$ VAR="a b c d"
$ set $VAR
$ echo $#
4
答案 6 :(得分:0)
对于健壮的便携式 sh
解决方案,请参阅使用set -f
的{{3}}。
(回答(仅)“是否至少有1个空格?”问题的简单bash解决方案;注意:也将匹配前导和尾随空格,与下面的awk
解决方案不同:
[[ $v =~ [[:space:]] ]] && echo "\$v has at least 1 whitespace char."
)
这是一个强大的基于awk
的bash解决方案(由于调用外部实用程序效率较低,但在许多实际场景中可能无关紧要):
# Functions - pass in a quoted variable reference as the only argument.
# Takes advantage of `awk` splitting each input line into individual tokens by
# whitespace; `NF` represents the number of tokens.
# `-v RS=$'\3'` ensures that even multiline input is treated as a single input
# string.
countTokens() { awk -v RS=$'\3' '{print NF}' <<<"$1"; }
hasMultipleTokens() { awk -v RS=$'\3' '{if(NF>1) ec=0; else ec=1; exit ec}' <<<"$1"; }
# Example: Note the use of glob `*` to demonstrate that it is not
# accidentally expanded.
v='I am *'
echo "\$v has $(countTokens "$v") token(s)."
if hasMultipleTokens "$v"; then
echo "\$v has multiple tokens."
else
echo "\$v has just 1 token."
fi