Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...