bash 变量中的令牌数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/638802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:01:18  来源:igfitidea点击:

number of tokens in bash variable

bashsplit

提问by flybywire

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 变量中的标记数(以空格分隔的标记)——或者至少,它是一个还是更多。

回答by guns

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:

$# 扩展将告诉您变量/数组中的元素数。如果您使用的 bash 版本高于 2.05 左右,您可以:

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.

这有效地将字符串沿空格(这是默认分隔符)拆分为一个数组,然后计算数组的成员。

EDIT:

编辑:

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[*]}"

回答by Jo So

I can't understand why people are using those overcomplicated bashisms all the time. There's almost always a straight-forward, no-bashism solution.

我不明白为什么人们一直在使用那些过于复杂的 bashism。几乎总是有一个直截了当的、无偏见的解决方案。

howmany() { echo $#; }
myvar="I am your var"
howmany $myvar

This uses the tokenizer built-in to the shell, so there's no discrepancy.

这使用 shell 内置的标记器,因此没有差异。

Here's one related gotcha:

这是一个相关的问题:

myvar='*'
echo $myvar
echo "$myvar"
set -f
echo $myvar
echo "$myvar"

Note that the solution from @guns using bash array has the same gotcha.

请注意,@guns 使用 bash 数组的解决方案具有相同的问题。

The following is a (supposedly) super-robust version to work around the gotcha:

以下是一个(据说)超级强大的版本,可以解决这个问题:

howmany() ( set -f; set -- ; echo $# )

If we want to avoid the subshell, things start to get ugly

如果我们想避免使用子外壳,事情就会开始变得丑陋

howmany() {
    case $- in *f*) set -- ;; *) set -f; set -- ; set +f;; esac
    echo $#
}

These two must be used WITH quotes, e.g. howmany "one two three"returns 3

这两个必须使用 WITH 引号,例如howmany "one two three"返回3

回答by Mykola Golubyev

set VAR='hello world'
echo $VAR | wc -w

here is how you can check.

这是您可以检查的方法。

if [ `echo $VAR | wc -w` -gt 1 ] 
then
    echo "Hello"
fi

回答by ata

To count:

计算:

sentence="This is a sentence, please count the words in me."
words="${sentence//[^\ ]} "
echo ${#words}

To check:

去检查:

sentence1="Two words"
sentence2="One"
[[ "$sentence1" =~ [\ ] ]] && echo "sentence1 has more than one word"
[[ "$sentence2" =~ [\ ] ]] && echo "sentence2 has more than one word"

回答by mklement0

For a robust, portableshsolution, see @JoSo's functionsusing set -f.

有关强大、可移植的sh解决方案,请参阅@JoSo 的使用set -f.

(Simple bash-only solution for answering (only) the "Is there at least 1 whitespace?" question; note: will also match leading and trailing whitespace, unlike the awksolution below:

(用于回答(仅)“是否有至少 1 个空格?”问题的简单 bash-only 解决方案;注意:也将匹配前导和尾随空格,与以下awk解决方案不同:

 [[ $v =~ [[:space:]] ]] && echo "$v has at least 1 whitespace char."

)

)

Here's a robust awk-based bash solution (less efficient due to invocation of an external utility, but probably won't matter in many real-world scenarios):

这是一个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=$''` ensures that even multiline input is treated as a single input 
# string.
countTokens() { awk -v RS=$'' '{print NF}' <<<""; }
hasMultipleTokens() { awk -v RS=$'' '{if(NF>1) ec=0; else ec=1; exit ec}' <<<""; }

# 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

回答by Eugene Morozov

Simple method:

简单方法:

$ VAR="a b c d"
$ set $VAR
$ echo $#
4

回答by Ben S

Not sure if this is exactly what you meant but:

不确定这是否正是您的意思,但是:

$#= Number of arguments passed to the bash script

$#= 传递给 bash 脚本的参数数量

Otherwise you might be looking for something like man wc

否则你可能正在寻找类似的东西 man wc