Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: reading a file into an array. mapfile? (f)?



This doesn't seem to work for me. What am I doing wrong?

Here is my test program

zmodload -ap zsh/mapfile mapfile
echo 'line 1' > ./file.txt
echo '' >> ./file.txt
echo 'line 2' >> ./file.txt
text=( "${(f)mapfile[./file.txt]}" )
declare -p text
print ${#text[@]} lines

text=( "${(f)mapfile[/src/external-cvs/zsh/configure]}" )
print ${#text[@]} lines
wc -l /src/external-cvs/zsh/configure

And here is the output I get:

typeset -a text
text=('line 1' 'line 2' '')
3 lines
18726 lines
21124 /src/external-cvs/zsh/configure

Further tests show that the behavior seems to be to drop blank lines but put one at the end of the file.

Thanks.





On Fri, Sep 19, 2008 at 5:07 AM, Peter Stephenson <pws@xxxxxxx> wrote:
On Thu, 18 Sep 2008 20:47:00 -0400
"Rocky Bernstein" <rocky.bernstein@xxxxxxxxx> wrote:
> On Thu, Sep 18, 2008 at 12:44 AM, Bart Schaefer
> <schaefer@xxxxxxxxxxxxxxxx>wrote:
> > It's much simpler than you seem to believe:
> >
> > lines=( ${(f)mapfile[/path/to/file]} )
>
>
> Doesn't seem to work if the file (/path/to/file) has 0-length lines. These
> don't get stored in the array (lines).

Try

lines=( "${(f)mapfile[/path/to/file]}" )

Explanation:  without the quotes, elements that turn into an empty string
are removed.  (f) includes the effect of the (@) flag, which is a
generalised equivalent of the behaviour of "${array[@]}", so simply adding
the quotes is enough to get the empty lines.

I'd better update the change I made to the mapfile documentation.

--
Peter Stephenson <pws@xxxxxxx>                  Software Engineer
CSR PLC, Churchill House, Cambridge Business Park, Cowley Road
Cambridge, CB4 0WZ, UK                          Tel: +44 (0)1223 692070



Messages sorted by: Reverse Date, Date, Thread, Author