Enumerate files and directories with command 'ls'

Or simply do:

ls -b |nl -s '. ' -w 1
1. a\ file\ with\ nonewline
2. a\ file\ with\nnewline
3. a\ file\ with\ space
4. afile

from man nl:

-s, --number-separator=STRING
              add STRING after (possible) line number
-w, --number-width=NUMBER
              use NUMBER columns for line numbers

You should pipe the output of ls to another command. My suggestion is to use awk in this way:

$ ls -b --group-directories-first | awk '{print NR ". " $0}'
1. dir1
2. dir2
3. dir3
4. z-dir1
5. z-dir2
6. z-dir3
7. file1
8. file2
9. file3
10. file4
11. file5
12. file6
13. file7
14. file\nnewline
  • Please note that the file file\nnewline contains newline character \n in its name that is escaped by the option -b.

  • the option --group-directories-first will output the directories before the files.

Another possible way is to use for loop (but in this case to place the directories in the begging of the list will become more difficult):

n=1; for i in *; do echo $((n++)). $i; done

if just showing a number is the case, then you have several options as following as well as your less -N way:

$ ls |cat -n
$ ls |nl

If you want customized output numbering, then I would suggest to use find and do whatever you want to print:

find . -exec bash -c 'for fnd; do printf "%d. %s\n" "$((++i))" "$fnd"; done ' _ {} +

POSIXly, you would do:

find . -exec sh -c 'for fnd; do i=$((i+1)); printf "%d.\t%s\n" "$i" "$fnd"; done ' _ {} +

Tags:

Command Line