Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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"?

like image 453
Shengjie Avatar asked Jun 11 '12 16:06

Shengjie


People also ask

How do I Read a string from a file in Golang?

Inside the io/ioutil package, there's a function called ReadFile() which is used to open a file and then convert its contents into a slice of bytes, and if for some reason, it isn't able to do so, then it will return an error too. Here is the syntax of the ReadLine() function.


1 Answers

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

var=$(<file) 
like image 94
Dennis Williamson Avatar answered Sep 22 '22 14:09

Dennis Williamson