10

我正在尝试从文本文件hello.txt中读取值列表,并将它们存储在数组中。

counter=0

cat hello.txt | while read line; do
 ${Unix_Array[${counter}]}=$line;
 let counter=counter+1;
    echo $counter;
done

echo ${Unix_Array[0]}
echo ${Unix_Array[1]}
echo ${Unix_Array[2]}

我无法将值分配给数组Unix_Array[] ... echo语句不打印数组的内容。

4

5 回答 5

15

这里有一些语法错误,但明显的问题是分配正在发生,但你在隐含的 subshel​​l中。通过使用管道,您为整个while语句创建了一个子 shell。当while语句完成时,子 shell 退出并且你的Unix_Array不再存在。

在这种情况下,最简单的解决方法是不使用管道:

counter=0

while read line; do
  Unix_Array[$counter]=$line;
  let counter=counter+1;
  echo $counter;
done < hello.txt

echo ${Unix_Array[0]}
echo ${Unix_Array[1]}
echo ${Unix_Array[2]}

顺便说一句,你真的不需要柜台。更简单的写法可能是:

$ oIFS="$IFS" # Save the old input field separator
$ IFS=$'\n'   # Set the IFS to a newline
$ some_array=($(<hello.txt)) # Splitting on newlines, assign the entire file to an array
$ echo "${some_array[2]}" # Get the third element of the array
c
$ echo "${#some_array[@]}" # Get the length of the array
4
于 2012-06-18T17:33:12.293 回答
8

如果您使用的是 Bash v4 或更高版本,则可以使用mapfile来完成此操作:

mapfile -t Unix_Array < hello.txt

否则,这应该工作:

while read -r line; do
   Unix_Array+=("$line")
done < hello.txt
于 2012-06-18T17:39:15.133 回答
1

我发现的最好方法是:

declare -a JUPYTER_VENV
JUPYTER_VENV+=( "test1" "test2" "test3" )

然后使用它:

for jupenv in "${JUPYTER_ENV[@]}"
do
  echo "$jupenv"
done
于 2019-03-29T09:59:15.117 回答
0

这是一个解决方案:

count=0
Unix_Array=($(cat hello.txt))
array_size=$(cat hello.txt | wc -l)
for ((count=0; count < array_size; count++))
do
    echo ${Unix_Array[$count]}
done
于 2012-06-19T01:24:02.420 回答
0

而不是这个:

cat hello.txt | while read line; do
 ${Unix_Array[${counter}]}=$line;
 let counter=counter+1;
    echo $counter;
done

你可以这样做:

Unix_Array=( `cat "hello.txt" `)
于 2012-06-18T17:34:28.533 回答