【问题标题】:Shell Programming: Access Element of ListShell 编程:列表的访问元素
【发布时间】:2013-01-23 15:52:51
【问题描述】:

据我了解,在编写 Unix shell 程序时,您可以像使用 for 循环的列表一样遍历字符串。这是否意味着您也可以通过索引访问字符串的元素?

例如:

foo="fruit vegetable bread"

我如何访问这句话的第一个单词?我尝试使用像基于 C 的语言这样的方括号无济于事,而且我在网上阅读的解决方案需要正则表达式,我现在想避免使用。

【问题讨论】:

    标签: string list shell indexing


    【解决方案1】:

    $foo 作为参数传递给函数。比你可以使用$1$2等来访问函数中的对应词。

    function try {
     echo $1
    }
    
    a="one two three"
    
    try $a
    

    编辑:另一个更好的版本是:

    a="one two three"
    b=( $a )
    echo ${b[0]}
    

    编辑(2):看看this thread.

    【讨论】:

      【解决方案2】:

      使用数组是最好的解决方案。

      这是一个使用间接变量的棘手方法

      get() { local idx=${!#}; echo "${!idx}"; }
      
      foo="one two three"
      
      get $foo 1  # one
      get $foo 2  # two
      get $foo 3  # three
      

      注意事项:

      • $# 是给函数的参数数量(在所有这些情况下都是 4 个)
      • ${!#}是最后一个参数的
      • ${!idx}idx'th 参数的
      • 您不能引用$foo,以便shell 可以将字符串拆分为单词。

      有一点错误检查:

      get() {
        local idx=${!#}
        if (( $idx < 1 || $idx >= $# )); then
          echo "index out of bounds" >&2
          return 1
        fi
        echo "${!idx}"
      }
      

      请不要实际使用此功能。使用数组。

      【讨论】:

        猜你喜欢
        • 2017-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多