subcan
subcan

Reputation: 2141

find command listing results in directory order

I am trying to use the find command to find all files 'M*' from my working directory and display results in directory order.

Instead it keeps displaying results in sorted order which causes some deeper directories to be listed first because they are alphabetically in order.

$ find -name 'M*'
./MyFourth
./s/MyFirst
./s/v/b/MyThird
./s/v/MySecond

I would like it to be in this order:

./MyFourth
./s/MyFirst
./s/v/MySecond
./s/v/b/MyThird

Thanks for your help

Upvotes: 5

Views: 7648

Answers (2)

kev
kev

Reputation: 161664

$ find . -name 'M*' | awk -F/ '{print NF,$0}' | sort -k1,1n -k2 | cut -d' ' -f 2-
./MyFourth
./s/MyFirst
./s/v/MySecond
./s/v/b/MyThird

Upvotes: 1

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

If I understand correctly what you mean by "directory order", this should help:

find -name 'M*' -printf '%p\t%d\n' | sort -n -k2 | cut -f 1

It prints the files sorted by their depth in the directory tree.

Upvotes: 4

Related Questions