Search code examples
arraysbashtail

How to read the last two lines of a file into an array of length two in Bash?


I am trying to read the last two lines of a file in an array of length two.

Consider the file a.txt

bar
second line
hello world
foo bar fubar

I tried

lines=($(tail -n 2 a.txt))

but this results in an array of length 5, each containing a single word. I read the post Creating an array from a text file in Bash but fail to go from there to reading only the last two lines. Please note that efficiency (execution time) matters for my needs.

I am on Mac OS X using Terminal 2.6.1


Solution

  • You can use the mapfile command in bash for this. Just tail the last 2 lines and store them in the array

    mapfile -t myArray < <(tail -n 2 file)
    printf "%s\n" "${myArray[0]}"
    hello world
    printf "%s\n" "${myArray[1]}"
    foo bar fubar
    

    See more on the mapfile builtin and the options available.


    If mapfile is not available because of some older versions of bash, you can just the read command with process-substitution as below

    myArray=()
    while IFS= read -r line
    do 
        myArray+=("$line") 
    done < <(tail -n 2 file)
    

    and print the array element as before

    printf "%s\n" "${myArray[0]}"