Alex  Tiger
Alex Tiger

Reputation: 387

Read file into array with empty lines

I'm using this code to load file into array in bash:

IFS=$'\n' read -d '' -r -a LINES < "$PAR1"

But unfortunately this code skips empty lines.

I tried the next code:

IFS=$'\n' read -r -a LINES < "$PAR1"

But this variant only loads one line.

How do I load file to array in bash, without skipping empty lines?

P.S. I check the number of loaded lines by the next command:

echo ${#LINES[@]}

Upvotes: 3

Views: 1097

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295353

To avoid doing anything fancy, and stay compatible with all versions of bash in common use (as of this writing, Apple is shipping bash 3.2.x to avoid needing to comply with the GPLv3):

lines=( )
while IFS= read -r line; do
  lines+=( "$line" )
done

See also BashFAQ #001.

Upvotes: 2

anubhava
anubhava

Reputation: 785058

You can use mapfile available in BASH 4+

mapfile -t lines < "$PAR1"

Upvotes: 3

Related Questions