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"
?
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.
Process the lines inside the loop instead of after it. If you really need the file in a variable:
var=$(<file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With