Reputation: 53
I am trying to read from a file that is storing user names and addresses in the format of name:address on each new line and I wish to store only the addresses into an array. Is there any way to do this? My code currently looks like this:
while IFS=: read -r username address; do
array=${address}
done <userfile.txt
Which is only storing the address from the first line in the file and stopping.
Upvotes: 2
Views: 45
Reputation: 85895
You are almost right! You just need to append to the array using the +=
operator (append) which bash
arrays provide.
declare -a myArray=()
while IFS=: read -r username address; do
myArray+=("$address")
done < userfile.txt
Doing the above should do the trick for you. Note that the parentheses are also critical here. array+=(something)
appends a new element to the array, while array+=something
just appends text to the first element of the array. Optionally later to print the array contents each in separate line use printf
as
printf "%s\n" "${myArray[@]}"
Upvotes: 2
Reputation: 681
You can use array+=($address)
form of adding array element.
array=()
while IFS=: read -r username address; do
array+=("$address")
done < userfile.txt
echo ${array[@]}
Upvotes: 2