bash关联数组中的空格键[duplicate]

时间:2021-09-13 12:54:37

This question already has an answer here:

这个问题已经有了答案:

I'm trying to read a strcutured file into an associative array in bash. The file stores in each line a person name and a person address. For example:

我试着在bash中读取一个被分割的文件到关联数组中。文件在每行中存储一个人的名字和一个人的地址。例如:

person1|address1
person2|address2
...
personN|addressN

I am using the script below.

我正在使用下面的脚本。

#!/bin/bash
declare -A address
while read line
do
    name=`echo $line | cut -d '|' -f 1`
    add=`echo $line | cut -d '|' -f 2`
    address[$name]=$add
    echo "$name - ${address[$name]}"
done < adresses.txt

for name in ${!address[*]}
do
    echo "$name - ${address[$name]}"
done

The script work properly. However, in the FOR loop, i'm having some problems when the person name has spaces (For example "John Nobody"). How can I fix this?

脚本的正常工作。然而,在FOR循环中,当person名称有空格(例如“John Nobody”)时,我遇到了一些问题。我该怎么解决这个问题呢?

1 个解决方案

#1


3  

You need to use more quotes to maintain the values with whitespace as "words":

您需要使用更多的引号来维护空格作为“words”的值:

declare -A array
while IFS='|' read -r name value; do 
    array["$name"]="$value"
done <<END
foo bar|baz
jane doe|qux
END

for key in "${!array[@]}"; do echo "$key -> ${array[$key]}"; done
# .........^............^ these quotes fix your error.
foo bar -> baz
jane doe -> qux

The quotes in "${!array[@]}" in the for loop mean that the loop iterates over the actual elements of the array. Failure to use the quotes means the loop iterates over all the individual whitespace-separated words in the value of the array keys.

引用的“$ { !for循环中的数组[@]}表示循环遍历数组的实际元素。如果不使用引号,则循环将遍历数组键值中所有单独的空格分隔的单词。

Without the quotes you get:

没有引号:

for key in ${!array[@]}; do echo "$key -> ${array[$key]}"; done
foo -> 
bar -> 
jane -> 
doe -> 

#1


3  

You need to use more quotes to maintain the values with whitespace as "words":

您需要使用更多的引号来维护空格作为“words”的值:

declare -A array
while IFS='|' read -r name value; do 
    array["$name"]="$value"
done <<END
foo bar|baz
jane doe|qux
END

for key in "${!array[@]}"; do echo "$key -> ${array[$key]}"; done
# .........^............^ these quotes fix your error.
foo bar -> baz
jane doe -> qux

The quotes in "${!array[@]}" in the for loop mean that the loop iterates over the actual elements of the array. Failure to use the quotes means the loop iterates over all the individual whitespace-separated words in the value of the array keys.

引用的“$ { !for循环中的数组[@]}表示循环遍历数组的实际元素。如果不使用引号,则循环将遍历数组键值中所有单独的空格分隔的单词。

Without the quotes you get:

没有引号:

for key in ${!array[@]}; do echo "$key -> ${array[$key]}"; done
foo -> 
bar -> 
jane -> 
doe ->