Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find command listing results in directory order

Tags:

linux

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

like image 657
subcan Avatar asked Mar 06 '12 10:03

subcan


2 Answers

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.

like image 197
Michał Kosmulski Avatar answered Oct 12 '22 09:10

Michał Kosmulski


$ 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
like image 27
kev Avatar answered Oct 12 '22 10:10

kev