Bash – Iterate Through Sorted List of Files with Spaces

bashscriptingshell-script

I am doing this in OSX which uses bash but obviously, not all bash conventions are used so hopefully your suggestion is available to me 🙂

I have the following files

  1. fun bar1.txt
  2. Foo bar2.tXT (that's an uppercase XT)
  3. fun fun.txt

What I was is to iterate through the file list in a sorted manner?

something like:

for i in (my-sorted-file-list); do
    echo $i
done

Any ideas how this can be done? thanks a lot

Best Answer

Very simple:

for i in *; do
  echo "<$i>"
done

This uses bash's file globbing. A sort is not necessary as bash already sorts pathname expansions.
From man bash:

   Pathname Expansion
       After word splitting, unless the -f option has been set, bash scans each word for
       the characters *, ?, and [. If one of these characters appears, then the word is
       regarded as a pattern, and replaced with an alphabetically sorted list of file
       names matching the pattern.

 

Example result:

$ touch 'fun bar1.txt' 'Foo bar2.tXT' 'fun fun.txt'

$ for i in *; do echo "<$i>"; done
<Foo bar2.tXT>
<fun bar1.txt>
<fun fun.txt>

Note that the sort order is dependent upon LC_COLLATE (just like the sort utility). If you want a case insensitive sort, use LC_COLLATE=en_US.utf8. If you want a case sensitive sort, use LC_COLLATE=C.

Also man bash:

   LC_COLLATE
          This variable determines the collation order used when sorting the results
          of pathname expansion, and determines the behavior of range expressions,
          equivalence classes, and collating sequences within pathname expansion and
          pattern matching.
Related Question