Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...