Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在sh linux shell中迭代两个参数_Linux_Shell_Sh - Fatal编程技术网

如何在sh linux shell中迭代两个参数

如何在sh linux shell中迭代两个参数,linux,shell,sh,Linux,Shell,Sh,我有两组论点:a=571和b=dogs-cats-horse 它们应该成对出现:5匹狗,7匹猫和1匹马 他们还应该在一行中做到这一点: I have 5 whatever dogs whatever whatever I have 7 whatever cats whatever whatever I have 1 whatever horse whatever whatever 问题是$a和$b可以有数百个参数,所以写很多像上面这样的行实际上不是一个选项 我找到了以下类似的方法来完成这项工作

我有两组论点:a=571和b=dogs-cats-horse

它们应该成对出现:5匹狗,7匹猫和1匹马

他们还应该在一行中做到这一点:

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,我可以很容易地找到要更改的内容。

可能会使用以下方法:

#!/bin/bash

a="5 7 1"
b="dogs cats horse"

c=( $a )
d=( $b )

for i in ${!c[@]}; do
    echo "There are ${c[$i]} of ${d[$i]}"
done

如果可以使用“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

您还可以将映射嵌入到中,我认为这个解决方案会很好,但是我必须将值存储在主脚本中,而不是其他文件中。那么最好的方法是什么呢?您可以使用这里的文档。在循环体之后添加
while IFS=: read k v ; do
  echo "I have $v whatever $k whatever whatever"
done <<EOF
dogs:5
cats:7
horse:3
EOF