2017-06-08 5 views
1

bashのファイルにある行を配列に書き込もうとしています。私はここで何が起こっているのか理解していない:ファイルからループを読み込むBash配列がありません

[email protected]:~$ declare -a a 
[email protected]:~$ cat t.txt 
a b 
c d 
e f 
g h 
[email protected]:~$ cat t.txt | while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done 
a b 
0: a b 
a b 
c d 
1: c d 
a b c d 
e f 
2: e f 
a b c d e f 
g h 
3: g h 
a b c d e f g h 
[email protected]:~$ echo "${a[@]}" 

[email protected]:~$ 

EDIT: どうやらそれを、私はそれではなく、パイプファイルリダイレクトする場合は、 "作品":

[email protected]:~$ while read -r line; do echo $line; a=("${a[@]}" "$line"); echo "$i: ${a[$i]}"; echo "${a[@]}"; ((i++)); done < t.txt 
a b 
0: a b 
a b 
c d 
1: c d 
a b c d 
e f 
2: e f 
a b c d e f 
g h 
3: g h 
a b c d e f g h 
[email protected]:~$ echo "${a[@]}" 
a b c d e f g h 
[email protected]:~$ 

EDIT 2 を@ anubhava - どのバージョンのbashが必要でしょうか?私はあなたの提案を試みました、そして、私たちはmapfileを持っていましたが、それは "うまくいきませんでした"。

[email protected]:~$ bash --version 
bash --version 
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu) 
[email protected]:~$ unset a 
[email protected]:~$ a=() 
[email protected]:~$ mapfile -t a < t.txt 
[email protected]:~$ echo "${a[@]}" 

[email protected]:~$ 

どちらも第二の方法でした:

[email protected]:~$ unset a 
[email protected]:~$ a=() 
[email protected]:~$ echo "${a[@]}" 

[email protected]:~$ 
[email protected]:~$ while IFS= read -r line; do a+=("$line"); done < t.txt 
[email protected]:~$ echo "${a[@]}" 

[email protected]:~$ 

EDIT 3

私のMacはエルキャピタンを実行している上、上記の方法 "仕事" の両方を。

答えて

1

あなたはこのために組み込みmapfileを使用することができます。

mapfile -t arr < file 

古いBASHのバージョンである場合、あなたはこのようなwhileループを使用することができます

arr=() 

while IFS= read -r line; do 
    arr+=("$line") 
done < file 
+1

アハを!我々は交差した。しかし、あなたは私に2つのことを教えてくれました。 (1)私はmapfileについて聞いたことがない。 (2)私はあなたがそのような配列を追加できるかどうか分からなかった。 'bash'のどのバージョンが必要ですか?上記の私の編集を参照してください。 – abalter

+0

'mapfile'がbashに追加されました4 – anubhava

+0

私のシステムにはbash 4.2.46がありますが、あなたが提案した方法で配列を埋めていませんでした。しかし、私のMacは4.4.12で動作しており、動作しています。 – abalter

関連する問題