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

Re: mysterious newline



2026-11-19 15:09:21 -0700, Ray Andrews:
> This reads the lines in an array and if the first words on each line are not
> identical a blank line in inserted otherwise the lines are tight:
> 
> local prev="${(M)final[1]#*$' '}"

In zsh, you can index scalars by [w]ords instead of the default
of *characters* with the w subscript flag, so instead of that
you could use ${final[1][(w)1]}

The default separator for those [w]ords is $IFS so $var[(w)1]
is similar to ${${=var}[1]}.

> local final2=()
> for ((ii=1; ii<=$#final; ii++)); do
>     ffile="${(M)final[ii]#*$' '}"
>     if [[ "$prev" == "$ffile" ]]; then
>         final2+=$final[ii]
>     else
>         final2+=" "
>         prev=$ffile
>     fi
> done
[...]

I'd do something like:

first_pass=1 final2=()
for elt ( "$final[@]" ) {
  first_word=$elt[(w)1]
  (( first_pass )) || [[ $first_word = $prev ]] || final2+=
  prev=$first_word first_pass=0 final2+=$elt
}

Example:

$ typeset -p1 final final2
typeset -a final=(
  'foo A'
  $' foo\nB C'
  bar
)
typeset -a final2=(
  'foo A'
  $' foo\nB C'
  ''
  bar
)

Note how "foo" is the first word of the first two elements of
$final; in the second element, preceded by space and followed
with newline.




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