0

I have a problem with one of my bash scripts.

I have a file where is stored a list of email addresses line by line like so :

mail@adress1
mail@adress2

...

what I'd like to do is to actually put each line of the file in an array where each index corresponds to a line in the right order.

ChrisM
  • 1,576
  • 6
  • 18
  • 29

2 Answers2

1

For me mapfile was not available, you can also do this with potentially older Bash versions:

 set -f
 IFS=$'\n'                                                                                                                                             
 arr=($(<foo.txt))
stephanmg
  • 746
  • 6
  • 17
1

To read the lines of a file into an array:

mapfile -t myArray < myFile

or

myArray=()
while IFS= read -r line || [[ "$line" ]] ; do
    myArray+=( "$line" )
done < myFile

To read the fields of a line into an array: use read with -a and a "herestring" <<<

# suppose: line="foo,bar,baz"
IFS=, read -r -a fields <<< "$line"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks, the first solution worked for me, I didn't know such tool existed, I was stuck with my loops... I was wondering if I could use mapfile to fill an array with lists of words in column this time (I'm not asking you the solution, that wouldn't be fair, just if it' possible or not tu use mapfile again). Thanks again – Nicolas Tapino Nov 05 '19 at 17:49
  • You can use `read -a` to split a line into words – that other guy Nov 05 '19 at 18:18
  • 1
    Yes, I just added that to the answer – glenn jackman Nov 05 '19 at 18:19