Jafar Albadarneh
Jafar Albadarneh

Reputation: 415

Extract file contents into array using Bash

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

Upvotes: 23

Views: 58688

Answers (3)

Junior Dussouillez
Junior Dussouillez

Reputation: 2397

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

Upvotes: 25

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

Reputation: 40778

For bash version 4, you can use:

readarray -t array < file.txt

Upvotes: 43

potong
potong

Reputation: 58463

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.

Upvotes: 2

Related Questions