简体   繁体   English

计算bash数组中不以特定字符开头的元素

[英]counting elements in bash array that don't begin with a specific character

I'm trying to write a bash script that counts all elements in an array that don't begin with the character '-' (it's part of a shell-completion script that counts the arguments and not the options in the words array). 我正在尝试编写一个bash脚本,该脚本对不以字符'-'开头的数组中的所有元素进行计数(这是shell补全脚本的一部分,该脚本对words而不是words数组中的选项进行计数)。 A Python equivalent to what I'm trying to write would be: 与我要编写的Python等效的是:

len([word for word in words if not word.startswith("-")])

I wrote some code that works fine but since I'm very new to bash scripting, I'm sure that some improvements can be made, and I'm wondering if I missed some better way to implement this that doesn't involve so many lines of code, maybe something that looks more like the Python implementation? 我写了一些可以正常工作的代码,但是由于我对bash脚本非常陌生,因此我敢肯定可以进行一些改进,并且我想知道我是否错过了一种更好的方法来实现这一目标,而该方法并不涉及太多几行代码,也许看起来更像Python实现?

This is what I have: 这就是我所拥有的:

words=('a' 'b' '-c' 'd' '--foo' 'e')
argcount=0
for word in ${words[@]}
do
    if [[ $word =~ ^[^-].*$ ]] ; then
        ((argcount++))
    fi
done
echo $argcount

Any improvement is welcome. 欢迎任何改进。

I'd use 我会用

for word in "${words[@]}"

which should work even if some argument contain whitespace. 即使某些参数包含空格,它也应该起作用。 Also, instead of a regular expression, you can use a normal pattern matching: 另外,可以使用普通模式匹配来代替正则表达式:

if [[ $word != -* ]] ; then

Other than that, I do not see anything. 除此之外,我什么也看不到。 Bash is not as concise as Python or Perl. Bash不如Python或Perl那么简洁。

You can also use grep to count the lines for you: 您还可以使用grep为您计算行数:

$ words=('a' 'b' '-c' 'd' '--foo' 'e')
$ argcount=$( printf "%s\n" "${words[@]}" | grep -vc "^-" )

(Assuming no word in words can contain an embedded newline, which seems like a safe enough assumption.) (假设没有字words可以包含嵌入的换行符,这似乎是一个足够安全的假设。)

If you must use pure bash , and don't want to use patterns as choroba suggests, you can negate the result of the regular expression match: 如果您必须使用纯bash ,并且不想按照choroba的建议使用模式,则可以否定正则表达式match的结果:

if ! [[ $word =~ ^- ]]; then
    (( argcount++ ))
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM