|
|
|
|
||||||
| comp.unix.shell Using and programming the Unix shell. |
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
Hi there,
How can I get the contents of a file into a variable, newlines included. I've tried $ cat test.txt Hello World File $ myvar=`cat test.txt` $ echo $myvar Hello World File cat alone will display the file, newlines included, but using backticks and assigning the output to a variable strips the newline characters ?! Thanks in advance, C |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
Garhone wrote:
> $ myvar=`cat test.txt` > $ echo $myvar Use myvar="$(cat test.txt)" echo "${myvar}" Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
On 17 May 2007 10:32:41 -0700, garhone
<cacheung@consumercontact.com> wrote: > > > Hi there, > > How can I get the contents of a file into a variable, newlines > included. I've tried > > $ cat test.txt > Hello > World > File > $ myvar=`cat test.txt` > $ echo $myvar > Hello World File > > cat alone will display the file, newlines included, but using > backticks and assigning the output to a variable strips the newline > characters ?! > echo "$myvar" -- I watch television because you don't know what it will do if you leave it in the room alone. |
|
|
|
#4 |
|
Messages: n/a
Hébergeur: |
In news:1179423161.812555.282340@o5g2000hsb.googlegro ups.com,
garhone <cacheung@consumercontact.com> wrote: > $ myvar=`cat test.txt` > $ echo $myvar > Hello World File echo "${myvar}" |
|
|
|
#5 |
|
Messages: n/a
Hébergeur: |
On 2007-05-17, garhone wrote:
> Hi there, > > How can I get the contents of a file into a variable, newlines > included. I've tried > > $ cat test.txt > Hello > World > File > $ myvar=`cat test.txt` > $ echo $myvar > Hello World File > > cat alone will display the file, newlines included, but using > backticks and assigning the output to a variable strips the newline > characters ?! Echo prints its arguments separated by spaces. To preserve the newlines, quote the variable: echo "$myvar" Or, better: printf "%s\n" "$myvar" Note, however, that command substition removes trailing newlines. Do this to preserve them: myvar=`cat test.txt; echo .` myvar=${myvar%.} -- Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell/> Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress) ===== My code in this post, if any, assumes the POSIX locale ===== and is released under the GNU General Public Licence |
|
|
|
#6 |
|
Messages: n/a
Hébergeur: |
garhone wrote:
[...] > $ echo $myvar use instead this: echo "${myvar}" -- Spam protection: replace the word `nospam' for exal |
|
![]() |
| Outils de la discussion | |
|
|