George
George

Reputation: 25

Read lines from text file and store it in array

So i need to read all the lines from a text file(as an argument when i call the script) which contains numbers in this form(1 new line not 2):
num1:num2

num3:num4 etc

I use this command block:

while IFS= read line 
do
    IFS=':' read -r -a X <<< "$line" 
done < "$1"

to read the lines and numbers and store it into array X but the array goes only to position 0 and 1 and when it changes line it just write the new number(eg num3) where the old number was(eg num1 in pos 0)

Any solution to this?

Upvotes: 1

Views: 1757

Answers (1)

Cyrus
Cyrus

Reputation: 88626

With bash. Replace all : with line break and use mapfile to fill array x.

mapfile -t x < <(tr ':' '\n' < file)
declare -p x

Output:

declare -a x='([0]="num1" [1]="num2" [2]="num3" [3]="num4")'

See: help mapfile

Upvotes: 2

Related Questions