Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: mysterious newline
- X-seq: zsh-users 30766
- From: Stephane Chazelas <stephane@xxxxxxxxxxxx>
- To: Ray Andrews <rayandrews@xxxxxxxxxxx>
- Cc: Zsh Users <zsh-users@xxxxxxx>
- Subject: Re: mysterious newline
- Date: Fri, 20 Nov 2026 09:29:07 +0000
- Archived-at: <https://zsh.org/users/30766>
- In-reply-to: <0fad2590-65a7-4634-b8b8-97c734a03a01@eastlink.ca>
- List-id: <zsh-users.zsh.org>
- Mail-followup-to: Ray Andrews <rayandrews@xxxxxxxxxxx>, Zsh Users <zsh-users@xxxxxxx>
- References: <0fad2590-65a7-4634-b8b8-97c734a03a01@eastlink.ca>
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