Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

bash - Array from a file

If I have a file like this:

A:a
B:b
C:c

I need to create 2 arrays like

one=('A' 'B' 'C')
two=('a' 'b' 'c')

How can I do it in bash?

I've tried this:

declare -a one
declare -a two

while read line
do
    IFS=':' read -ra ADDR <<< $line
    echo ${ADDR[0]}
    echo ${ADDR[1]}
done < file.txt

Sorry I wrote from work and then I came home. Sorry again. The problem with this is that it's printing

littlelion:Documents dierre$ sh prova.sh 
A a

B b

so it's missing C c and I have no idea how to add an element to an array

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Quotes fix everything:

while read line
do
    IFS=':' read -ra ADDR <<< "$line"
    echo ${ADDR[0]}
    echo ${ADDR[1]}
done < file.txt

Quoting the variable "$line" is what made the difference. If you're not getting the line with "C:c", it's probably because your file is missing a final newline.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...