Enumerate files and directories with command 'ls'

Run Command ls on Current Directory and get the output:

$ ls
Applications Documents    Library      Music        Public
Desktop      Downloads    Movies       Pictures

I'd like to enumerate them like:

1. Applications
2. Desktop
3. Documents
4. Downloads
5. Library
6. Movies
7. Music
8. Pictures
9. Public

This could be achieved using less in an intermediate way

ls | less -N

How to enumerate them in a straightforward way?


Solution 1:

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

Solution 2:

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

Solution 3:

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 ' _ {} +