You can do it two ways:-
1st one :-
ls -1 | awk '{print NR,$0}'
2nd one:-
ls -1 | cat -n
You must prefer 2nd one but choose whatever you like. :-)
Question
I want to get a numbered list of files, e.g. if I have these files:
a.pdf
b.pdf
c
then it should be listed as:
1 a.pdf
2 b.pdf
3 c
Solution
You can do it two ways:-
1st one :-
ls -1 | awk '{print NR,$0}'
2nd one:-
ls -1 | cat -n
You must prefer 2nd one but choose whatever you like. :-)
OTHER TIPS
If you want to avoid parsing the output of ls
(which you do), you can do something like this:
$ counter=1; for f in *; do printf "%2d %s\n" $((counter++)) "$f"; done
1 a.pdf
2 b.pdf
3 c
I only mention this because it's the path for doing more sophisticated things, not just enumerating.
If your system has command nl
, it will be easier. ( I can confirm nl
command is exist in cygwin, aix and solaris system, then it should be popular command in most unix system)
ls |nl
You can do this without awk, trivially. ls -1 | cat -n
.
Or, with awk:
ls -1 | awk '{printf "%d %s\n", NR, $0;}'
Not sure why you need to use awk
but here you go:
ls | awk '{print NR, $0}'
updated $0
is better than $1
since it will print the entire file name even with spaces (as hinted at by BroSlow)
Note - you do not need to use the -1
flag with ls
when the output is another process - it becomes the default option. Only when you want to force output to the terminal with one file per line do you need to use it.