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

Re: for loop file order



2026-11-15 19:59:52 -0700, Ray Andrews:
>     for aa in *; do cat $aa >> output; done
> 
> ... is there some way of controlling the order in which the files are
> processed?  I'd expect alphabetical order to be the default, but suppose
> size or date were wanted?

"for" loops over the elements you pass to it in the order you
pass them to it.

In

for i (2 1) echo $i

It outputs 2 and 1.

In your case, it loops over the expansion of the "*" glob. glob
expansions are sorted lexically by default, but the sorting
order can be affected by the o, O and n glob qualifiers (see
also the numericglobsort option).

Run

  info zsh qualifiers

for details.

To concatenate all the non-hidden files in the current working
directory, [o]rdered by [L]ength:

set -o extendedglob
cat ./^output(-.oL) > output

(note that we wnat to exclude "output" itself from the glob
expansion, or you'd run into a feed loop and we don't need a
loop here, "cat" is the command to con[cat]enate).

The other glob qualifiers used here are:

- "-" so the following qualifiers consider files *after* symlink
  resolution.
- "." to restrict the glob expansion to files of type "regular"
  (so including symlinks eventually resolving to regular files
  with the previous "-").

"-" also affects the [o]rdering as it's the [L]ength (apparent
size in bytes) of the target of the symlinks that is taken into
account for the ordering.

-- 
Stephane




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