我有两组参数:a = "5 7 1"
和 b = "dogs cats horse"
它们应该成对出现:5
匹配 dogs
,7
匹配 cats
和 1
匹配 horse
他们还应该在一行中完成此操作:
I have 5 whatever dogs whatever whatever
I have 7 whatever cats whatever whatever
I have 1 whatever horse whatever whatever
问题是 $a
和 $b
可以有数百个参数,因此编写像上面这样的许多行并不是真正的选择。
我发现类似下面的东西可以完成这项工作:
a = "5 7 1"
b = "dogs cats horse"
set -- $a
for i in $b; do
echo "I have $i whatever $1 whatever whatever"
shift 1
done
但我想知道是否还有其他选择。
基本上,当我们只有 3 对时,在脚本中很容易知道 $a
中的哪些值对应于 $b
中的哪些值。现在想象一下,两个集合中都有 200 个值,您必须更改 $b
值,其中 $a
值为 50
和 157
。当然,这只是一个例子——两个集合中的任何值都可以随着时间而改变。那么是否有更好的方法来映射 5:dogs
、7:cats
和 1:cats
等值?这样,如果狗的数量变为 4,我可以轻松找到要更改的内容。
最佳答案
如果您可以使用“bash”,则可以使用关联数组(和mapfile/readarray),但这不能很好地扩展到您提到的项目数量(200+)。
对于非 bash 特定的解决方案:考虑将这些对存储在文件(或内联文档,见下文)中。
dogs:5
cats:7
horse:1
然后使用脚本:
while IFS=: read k v ; do
echo "I have $v whatever $k whatever whatever"
done < file.txt
您还可以将 map 嵌入到<<文档中。
while IFS=: read k v ; do
echo "I have $v whatever $k whatever whatever"
done <<EOF
dogs:5
cats:7
horse:3
EOF
关于linux - 如何在 sh linux shell 中迭代两个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58452675/