bash 变量中的令牌数 [英] number of tokens in bash variable

查看:22
本文介绍了bash 变量中的令牌数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何知道 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆