我沒有在網站上找到解決方案。將行存入數組時保留空間
如何將文本內容存儲到bash中的數組中?
該代碼實際上是這樣做的,但刪除字符串之前的空間。
index=0
while read line; do
echo $line
str_array[index]="$line"
done < /testfile
我沒有在網站上找到解決方案。將行存入數組時保留空間
如何將文本內容存儲到bash中的數組中?
該代碼實際上是這樣做的,但刪除字符串之前的空間。
index=0
while read line; do
echo $line
str_array[index]="$line"
done < /testfile
你可以做這樣的事情:
index=0
while IFS= read line ; do
str_array[$index]="$line"
index=$(($index+1))
done < testfile
或如@glennjackman的建議評論
index=0
while IFS= read line ; do
str_array[index++]="$line"
done < testfile
對於bash,使用內建mapfile
:
$ cat testfile
asdf
asdf
asdf
asdf
$ mapfile -t str_array < testfile
$ printf "%s\n" "${str_array[@]}"
asdf
asdf
asdf
asdf
在bash提示符,看到help mapfile
你節省了我的一天。 –
如果你想收緊一點:'str_array [index ++] =「$ line」'或'str_array + =(「$ line」)' –
@glennjackman謝謝Glenn,好點。 –