22

How to extract a file content into array in Bash line by line. Each line is set to an element.

I've tried this:

declare -a array=(`cat "file name"`)

but it didn't work, it extracts the whole lines into [0] index element

codeforester
  • 39,467
  • 16
  • 112
  • 140
Jafar Albadarneh
  • 395
  • 1
  • 4
  • 16

3 Answers3

40

For bash version 4, you can use:

readarray -t array < file.txt
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • 5
    This is the sensible and efficient way to proceed in modern bash. Note that `readarray` is synonym of `mapfile`. – gniourf_gniourf Nov 30 '13 at 12:47
  • @Håkon Hægland I liked it because you helped me :-) thanks a lot – Learner Feb 11 '19 at 21:55
  • 1
    also `readarray --help` is very poor. If you need to know more check `mapfile --help`. Since mapfile is a shell built-in `man mapfile` redirects into `man bash` which is a very big place. – Bruno Sep 28 '22 at 13:40
25

You can use a loop to read each line of your file and put it into the array

# Read the file in parameter and fill the array named "array"
getArray() {
    array=() # Create array
    while IFS= read -r line # Read a line
    do
        array+=("$line") # Append line to the array
    done < "$1"
}

getArray "file.txt"

How to use your array :

# Print the file (print each element of the array)
getArray "file.txt"
for e in "${array[@]}"
do
    echo "$e"
done
Junior Dussouillez
  • 2,327
  • 3
  • 30
  • 39
2

This might work for you (Bash):

OIFS="$IFS"; IFS=$'\n'; array=($(<file)); IFS="$OIFS"

Copy $IFS, set $IFS to newline, slurp file into array and reset $IFS back again.

potong
  • 55,640
  • 6
  • 51
  • 83