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?
Or simply do:
from
man nl
:You should pipe the output of
ls
to another command. My suggestion is to useawk
in this way: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):
if just showing a number is the case, then you have several options as following as well as your
less -N
way:If you want customized output numbering, then I would suggest to use
find
and do whatever you want to print:POSIXly, you would do:
You can also do this entirely with a short Bash script:
You can even be fancy and pad the line number for more than 9 results:
Usage
Assuming that you saved the script as an executable file
numbered-ls.sh
in the current working directory:The argument
DIRECTORY
is optional and defaults to the current working directory.Explanation
If the script was invoked with an argument change the working directory to the path in the first argument.
Match all entries of the current working directory and look over them. For each entry increment a counter and print its value along with the name of the entry. Line break characters in the name of the entry are replaced with
^N
.Pipe the output through
cat -vt
to deal gracefully with file names that contain non-printable characters that the terminal may interpret as control characters.