Re: Parsing a char array w/fields delimited by /0xA



Stephane Chazelas <stephane_chazelas@xxxxxxxx> wrote:
On Tue, 12 Sep 2006 20:16:36 -0400, William Park wrote:
Hufnus <tonyb@xxxxxxxxxx> wrote:
I have been crackin my head trying to write a bash script
to break a large string with a bunch of concatenated variable
length strings separated by linefeeds (0x0A), into an array.

$string -> $field[i] i=0...n

Key insight:
This is "split/join" operation which you see a lot in Python, Perl,
Ruby, ... context.

In Bash, it's even simpler with the right C extension, :-)

field=( "${string|,$'\n'}" )


In zsh:

field=(${(f)string})

(shortcut for field=(${(ps:\n:)string}))

However, this discards the empty tokens.

IFS=$'\n\n'
field=($=string)

Would preserve them.

This is slightly more standard than your bash extension as zsh
can be found on more than one computer in the world, but again
better is to use standard/open syntax and use the proper tool.

If you need arrays, you probably don't want a shell, use
perl/python/ruby...

If you're going to use a shell, do it the shell way, using
filters working concurrently.

Not sure if Zsh has this feature, but OP may want to experiment with
while read; do ... done <<< "$string"
since this is essentially reading line by line.

--
William Park <opengeometry@xxxxxxxx>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
http://freshmeat.net/projects/bashdiff/
.



Relevant Pages

  • Re: Parsing a char array w/fields delimited by /0xA
    ... length strings separated by linefeeds, into an array. ... This is slightly more standard than your bash extension as zsh ... better is to use standard/open syntax and use the proper tool. ... If you're going to use a shell, do it the shell way, using ...
    (comp.unix.shell)
  • Re: How to build an array
    ... Is there a way to build an array from a string with only shell ... It seems pretty strait forward to use sed: ... Note than in zsh, array indices start at 1 (except in ksh ...
    (comp.unix.shell)
  • Re: "canonical" approach to writing wrapper scripts
    ... > Is "$@" treated as an array? ... Standard Unix shell syntax doesn't have arrays. ... Only zsh has a 1 to 1 mapping to an array, ...
    (comp.unix.shell)
  • Re: bash: is nested parameter expansion possible?
    ... what you're seeing in bash is rightfully considered as a bug ... >> It is not a bug, but an important part of the design of the shell ... > zsh happens to be the only shell that does just that. ...
    (comp.unix.shell)
  • Re: switching shells
    ... > 3) and needs to use arrays fairly often in scripts ... Can /sh handle arrays, or if I'm going to have arrays ... > interactive shell) I'd like to know what shell is recommended for me. ... zsh has a POSIX conformant mode that can be used to run POSIX ...
    (comp.unix.shell)