我正在尝试从文本文件中读取值列表,你好.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[]... The echo语句不打印数组的内容。
这里有一些语法错误,但明显的问题是赋值正在发生,但是你在一个隐含的子shell中 http://mywiki.wooledge.org/BashPitfalls#grep_foo_bar_.7C_while_read_-r.3B_do_.28.28count.2B-.2B-.29.29.3B_done。通过使用管道,您已经为整个进程创建了一个子shellwhile陈述。当。。。的时候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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)