Shengjie
Shengjie

Reputation: 12796

How to read the file content into a variable in one go?

In Java, if you know for certain a file is very small, you can use readBytes() method to read the content in one go instead of read it line by line or using buffer.

Just wondering in shell script, I know we can do something like:

    while read line
    do
      echo $line
      LINE = $line
    done < "test.file"
    echo $LINE

If my test.file is like:

testline1
testline2
testline3

This only gives me the last line to $LINE. $LINE contains "testline3".

My question is: How can I read the whole file with multiple lines into one single variable,so I can get $LINE="testline1\ntestline2\ntestline3"?

Upvotes: 49

Views: 117517

Answers (3)

Mark Reed
Mark Reed

Reputation: 95375

As another option, you can build an array of lines. If you're running bash 4+, you can use the mapfile builtin:

mapfile -t lines <test.file

If you want the lines to be output as well as stored you could do something like this:

mapfile -t lines < <(tee /dev/tty <test.file)

Then "${lines[0]}" will be the first line of the file, "${lines[1]}" the second, and so on. ${#lines[@]} will be the number of lines; "${lines[@]}" will be the whole array, while "${lines[*]}" will be the lines joined together with spaces into one big string.

For older versions of bash, you can build the array manually:

lines=()
while IFS= read -r line
do
  printf '%s\n' "$line"
  lines+=("$line")
done < test.file

Upvotes: 12

Stephen Niedzielski
Stephen Niedzielski

Reputation: 2637

Another alternative is to use the nice mapfile builtin:

mapfile < test.file
echo "${MAPFILE[@]}"

Upvotes: 13

Dennis Williamson
Dennis Williamson

Reputation: 360665

Process the lines inside the loop instead of after it. If you really need the file in a variable:

var=$(<file)

Upvotes: 132

Related Questions