help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Simplest way to keep trailing newlines when reading a fi


From: Greg Wooledge
Subject: Re: [Help-bash] Simplest way to keep trailing newlines when reading a file into a bash variable
Date: Mon, 21 May 2018 09:27:09 -0400
User-agent: NeoMutt/20170113 (1.7.2)

On Sat, May 19, 2018 at 05:04:52AM -0500, Peng Yu wrote:
> It is simple to read a file with training newlines removed into a bash 
> variable.
> 
> x=$(< file)
> 
> Supposedly, it should be reasonable to expect a solution with as
> little code as possible (e.g., no intermediate variable, one line).
> But I haven't found such a solution. Does anybody know such a simplest
> solution? Thanks.

Solution 1:

x=$(cat file; printf z) x=${x%z}

Number of intermediate variables: 0

Number of lines of code: 1

Number of bytes dropped on the floor: 1 (0x00, NUL)


Solution 2:

IFS= read -rd '' x < <(tr -d \\0 < file)

Number of intermediate variables: 0

Number of lines of code: 1

Number of bytes dropped on the floor: 1 (0x00, NUL)


Solution 3:

Stop writing in bash.  Use a real programming language instead.

Number of intermediate variables: depends on the language

Number of lines of code: depends on the language

Number of bytes dropped on the floor: depends on the language

For example, in Tcl:

set x [read $my_file_descriptor]

will read the entire contents of the already-open file descriptor and
store it in the variable x.  This includes NUL bytes.  This includes
trailing newlines.  This includes everything Tcl can handle, which is
the Unicode Basic Multilingual Plane plus the NUL byte (which is encoded
specially).  If you need Unicode outside of the BMP, well, you're out of
luck.  Stop writing in Tcl (for now).

Maybe Perl can do it?  Maybe Python?  Ruby?  I don't know.


> Supposedly, it should be reasonable to expect a solution with as
> little code as possible

Why on EARTH would you hold such an expectation?  You've been doing
bash programming for a while now.  Surely you've developed some idea
of how fragile and hackish it is.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]