Afficher un message
Vieux 17/05/2007, 20h37   #5
Chris F.A. Johnson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: backticks remove new line characters

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
  Réponse avec citation
 
Page generated in 0,05415 seconds with 9 queries