Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract file contents into array using Bash

Tags:

arrays

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

like image 851
Jafar Albadarneh Avatar asked Nov 29 '13 23:11

Jafar Albadarneh


People also ask

Can bash function return array?

You may believe that Bash loses the capability to return function arrays. However, that is not exactly correct. It is possible to move the resultant array to a method by reference, taking cues from C/C++ developers. Such a strategy allows the method to continue to be free from references towards a global variable.

How do I echo an array in bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


2 Answers

For bash version 4, you can use:

readarray -t array < file.txt
like image 197
Håkon Hægland Avatar answered Sep 27 '22 19:09

Håkon Hægland


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
like image 28
Junior Dussouillez Avatar answered Sep 27 '22 18:09

Junior Dussouillez