2013-05-29 30 views
1

我沒有在網站上找到解決方案。將行存入數組時保留空間

如何將文本內容存儲到bash中的數組中?

該代碼實際上是這樣做的,但刪除字符串之前的空間。

index=0 

while read line; do 
echo $line 
str_array[index]="$line" 
done < /testfile 

回答

1

你可以做這樣的事情:

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 
+0

你節省了我的一天。 –

+1

如果你想收緊一點:'str_array [index ++] =「$ line」'或'str_array + =(「$ line」)' –

+0

@glennjackman謝謝Glenn,好點。 –

1

您需要取消定義字段分隔符,所以這將是這樣的:

while IFS= read line; do 
    echo "$line" 
    ... 
done < /testfile 
+0

另外,我建議'回聲 「$線」',而不僅僅是'回聲$ line'。 – Alfe

+0

@Alfe:是的。你是對的。更新。 – Birei

+0

非常感謝你。 –

2

對於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