简体   繁体   中英

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 |

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM