Biglava
Biglava

Reputation: 43

How to list all files and put number in front of them , using shell

I want to count all files that I have in my directory and put number in front of them, and in a new line, for example :

file.txt nextfile.txt example.txt

and the output to be :

1.file.txt
2.nextfile.txt
3.example.txt

and so on. i am trying something with : ls -L |

Upvotes: 0

Views: 1205

Answers (2)

Zsolt Botykai
Zsolt Botykai

Reputation: 51593

You can do this if you have nl installed:

ls -1 | nl

(Note with modern shells (ls usually a built-in) the -1 part is not needed. And this applies to the below solutions too.)

Or with awk:

ls -1 | awk '{print NR, $0}'

Or with a single awk command:

awk '{c=1 ; for (f in ARGV) {print c, f ; c++ } }' *

Or with cat:

cat -n <(ls -1)

Upvotes: 2

anubhava
anubhava

Reputation: 785058

You can do this by using shell built-in printf in a for loop:

n=0
for i in *; do
   printf "%d.%s\n" $((n++)) "$i"
done

Upvotes: 1

Related Questions