mugnozzo
mugnozzo

Reputation: 220

Sort directory list by subfolder number

Is there a fast and smart way in bash (maybe with awk/sed/sort???) to sort the result of a find command by number of subfolders in the path and then alphabetically.

I mean something like

./a/
./b/
./c/
./a/a/
./a/python-script.py
./a/test.txt
./b/a/
./b/b/
./c/a/
./c/c/
./a/a/a/
./a/a/file.txt
./a/a/t/
...
...

I want to take the output of the find command and see first the filenames in the current folder, then the files in the first level of subfolders, then the files in the second level, and so on (if possible sorted alfabetically for each level).

Upvotes: 0

Views: 934

Answers (2)

tshiono
tshiono

Reputation: 22042

I suppose this is much less elegant than @kvantour's answer, how about the Schwartzian transform in Perl:

find . -print0 | perl -0ne '
    push(@list, $_);
    END {
        @sorted = map { $_->[0] }
        sort { $a->[1] <=> $b->[1] or $a->[0] cmp $b->[0] }
        map { [$_, tr#/#/#] } @list;
        print join("\n", @sorted), "\n";
    }'

Upvotes: 0

kvantour
kvantour

Reputation: 26531

You can use the printf statement in find and ask it to return the depth of the file %d. Then use sort on that and cut to remove the output:

$ find . -printf '%d\t%p\n' | sort -n | cut -f2-

Upvotes: 4

Related Questions