Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

sorting - sort files by depth (bash)

Is there a way in bash to sort my files from a directory down in depth order, for example first print the files in the present directory, then the files in the sub directory or sub directories and so forth, always in perspective to their depth.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use find's "-printf" feature in combination with sort. See for yourself:

find . -printf "%d %p
"|sort -n

It generates a depth-sorted list (displaying the depth in the first column, file path in the second). This prints in my current dir:

0 .
1 ./bin
1 ./log
1 ./templates
2 ./bin/cc_env
3 ./files/test/mail.txt

If you want to strip the first column, we can use perl:

find . -printf "%d %p
"|sort -n|perl -pe 's/^d+s//;'

and off you go. The perl filter will remove all leading numbers. In case you want to omit directories themselves, use the '-type f' parameter:

find . -type f -printf "%d %p
"|sort -n|perl -pe 's/^d+s//;'

Hint: Study the find manpage for more printf %d-like tricks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...