【问题标题】:How to iterate over two arguments in the sh linux shell如何在 sh linux shell 中迭代两个参数
【发布时间】:2019-10-18 14:14:58
【问题描述】:

我有两组参数:a = "5 7 1"b = "dogs cats horse"

它们应该成对出现:5 匹配 dogs7 匹配 cats1 匹配 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 的值是 50157。当然这只是一个例子——任何值都可以随时间改变。那么有没有更好的方法来映射5:dogs7:cats1:cats 之类的值?这样,如果狗的数量变为 4,我可以很容易地找到要更改的内容。

【问题讨论】:

    标签: linux shell sh


    【解决方案1】:

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

    【讨论】:

    • 我认为这个解决方案会很好,但我必须将值存储在主脚本中,而不是一些额外的文件中。那么最好的方法是什么?
    • 您可以使用这里的文档。在循环体之后添加
    【解决方案2】:

    可能会使用这样的东西:

    #!/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
    

    【讨论】:

      猜你喜欢
      • 2010-10-07
      • 2021-09-06
      • 2012-09-28
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多