我正在尝试从文件读取并写入数组。
tempfile.txt的文件内容如下所示: / Users / adikshit / D / abc / Grand / abc bgrt。 thbn。 jm / Users / adikshit / D / abc / Grand / .DS_Store / Users / adikshit / D / abc / Grand / LICENSE
请注意空字符。
下面的代码片段完成了三件事
这对于没有空格的文件效果很好,但是似乎遇到空格时,我试图在数组中附加值的部分出现了错误,并将空格也视为定界符,因此得出结果。
代码段:
#Build a list of files in the folder and write to a temporary file with newline as the delimiter
$(find $CURRENT_FOLDER -maxdepth 1 -type f -print0 > $TEMP_FILE)
declare -a fileListInDirectory
while IFS='' read -r -d $'\0' line
do
echo "line value is $line"
fileListInDirectory+=($line)
done < "$TEMP_FILE"
# get length of an array
arraylength=${#fileListInDirectory[@]}
# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
echo $i " / " ${arraylength} " : " ${fileListInDirectory[$i-1]}
done
#Unset the Array and index variables.
unset fileListInDirectory
我也尝试过。
#$(read -r -d $' ' -a fileListInDirectory < $TEMP_FILE)
输出。
line value is /Users/adikshit/D/abc/Grand/abc bgrt . thbn . jm
line value is /Users/adikshit/D/abc/Grand/.DS_Store
line value is /Users/adikshit/D/abc/Grand/LICENSE
1 / 8 : /Users/adikshit/D/abc/Grand/abc
2 / 8 : bgrt
3 / 8 : .
4 / 8 : thbn
5 / 8 : .
6 / 8 : jm
7 / 8 : /Users/adikshit/D/abc/Grand/.DS_Store
8 / 8 : /Users/adikshit/D/abc/Grand/LICENSE
系统信息:
> DELC02WM1V8HTD7:Mac adikshit$ echo $SHELL /bin/bash
> DELC02WM1V8HTD7:Mac adikshit$ $SHELL --version GNU bash, version
> 3.2.57(1)-release (x86_64-apple-darwin18) Copyright (C) 2007 Free Software Foundation, Inc. DELC02WM1V8HTD7:Mac adikshit$