在bash变量的令牌数量 [英] number of tokens in bash variable
问题描述
我怎么能知道在bash变量标记(空格分隔的标记)的数量 - 或者至少,羯羊它是一个或有更多的
how can I know the number of tokens in a bash variable (whitespace-separated tokens) - or at least, wether it is one or there are more.
推荐答案
在$#扩张会告诉你一个变量/数组元素的数量。如果你有一个bash版本工作大于2.05左右,您可以:
The $# expansion will tell you the number of elements in a variable / array. If you're working with a bash version greater than 2.05 or so you can:
VAR='some string with words'
VAR=( $VAR )
echo ${#VAR[@]}
这有效地分割字符串转换成沿空白一个数组(这是默认的分隔符),然后计算数组的成员。
This effectively splits the string into an array along whitespace (which is the default delimiter), and then counts the members of the array.
编辑:
当然,这重铸变量作为数组。如果你不希望出现这种情况,使用不同的变量名或重铸变回一个字符串:
Of course, this recasts the variable as an array. If you don't want that, use a different variable name or recast the variable back into a string:
VAR="${VAR[*]}"
这篇关于在bash变量的令牌数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!