【问题标题】:How to iterate over list which contains whitespaces in bash如何迭代包含bash中空格的列表
【发布时间】:2013-01-13 07:44:25
【问题描述】:

您能告诉我如何遍历列表中的项目可以包含空格吗?

x=("some word", "other word", "third word")
for word in $x ; do
    echo -e "$word\n"
done

如何强制输出:

some word
other word
third word

代替:

some
word
(...)
third
word

【问题讨论】:

    标签: bash loops


    【解决方案1】:

    要正确循环项目,您需要使用${var[@]}。并且你需要引用它以确保带有空格的项目没有被拆分:"${var[@]}"

    大家一起:

    x=("some word" "other word" "third word")
    for word in "${x[@]}" ; do
      echo -e "$word\n"
    done
    

    或者,更理智的 (thanks Charles Duffy) 和 printf

    x=("some word" "other word" "third word")
    for word in "${x[@]}" ; do
      printf '%s\n\n' "$word"
    done
    

    【讨论】:

    【解决方案2】:

    两种可能的解决方案,一种类似于 fedorqui 的解决方案,没有额外的 ',',另一种使用数组索引:

    x=( 'some word' 'other word' 'third word')
    
    # Use array indexing
    let len=${#x[@]}-1
    for i in $(seq 0 $len); do
            echo -e "${x[i]}"
    done
    
    # Use array expansion
    for word in "${x[@]}" ; do
      echo -e "$word"
    done
    

    输出:

    some word
    other word
    third word
    some word
    other word
    third word
    

    编辑:修复了cravoori指出的索引解决方案的问题

    【讨论】:

    • 您的数组索引解决方案是假的。无论数组长度如何,它都会打印 3 个数组成员。您需要将seq 放入command substitution。另外,从 0 而不是 1 开始
    猜你喜欢
    • 2015-01-01
    • 2019-01-12
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2015-12-28
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多