小编Cyb*_*xar的帖子

为什么使用负模式匹配和参数扩展过滤 bash 数组会产生意外结果?

我正在做一个小型的纯 bash 脚本来掷骰子;因此我必须操作数组。我想做一些类似于filter其他语言中的操作:提取数组中的一些内容,并将它们放入另一个中。

我希望将这些值保留为 bash 数组,因为使用数组进行其他一些操作(即跨索引切片)要容易得多。

我可以通过for... do... done循环来完成此操作,但我很好奇为什么我的模式匹配不能按预期工作。

shopt -s extglob;
dicerolls=(a b lol kek yolo swag ); 
c=(${dicerolls[@]/!(kek)/}); 
declare -p c;
# Expected: declare -a c=([0]="kek")
# Got: declare -a c=([0]="k")

# One can also see it with this example:
dicerolls=(20 15 7 8 9 0 14 5 6 200 144); c=(${dicerolls[@]/!(14)/}); declare -p c;
# Expected: declare -a c=([0]="14")
# Got: declare -a c=([0]="4")

# Oddly, this works for single-character values
dicerolls=(20 15 …
Run Code Online (Sandbox Code Playgroud)

bash array wildcards

4
推荐指数
1
解决办法
504
查看次数

标签 统计

array ×1

bash ×1

wildcards ×1