sort files by depth (bash)

后端 未结 5 2194
半阙折子戏
半阙折子戏 2020-12-19 13:39

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

5条回答
  •  暖寄归人
    2020-12-19 14:21

    A plausible technique would use find to generate the file pathnames, and then process the file names so that a count of the number of slashes in the path precedes the name, and then you can sort by the count of slashes (depth) and then by name. The simple solutions assume that there are no newlines in your file names (other spaces and odd-ball characters do not matter). The interesting/tricky part is finding a clean way of counting the number of slashes in a given line.

    find . -type f -print |
    perl -n -e '$x = $_; $x =~ tr%/%%cd; print length($x), " $_";' |
    sort -k 1n -k 2 |
    sed 's/^[0-9][0-9]* //'
    

    There's probably a more compact way of writing that Perl, but that works.

提交回复
热议问题