sort files by depth (bash)

后端 未结 5 2190
半阙折子戏
半阙折子戏 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条回答
  •  旧时难觅i
    2020-12-19 14:35

    use a function to recursively traverse the filesystem

    test.sh:

    #!/bin/bash
    
    function traverse() {
        find $1 -mindepth 1 -maxdepth 1 ! -type d -exec echo "$2"{} \; 
        for d in $(find $1 -mindepth 1 -maxdepth 1 -type d ! -name ".")
        do
            # if you just need files comment out next line
            echo "$2$d"
            traverse "$d" "${2}  "
        done
    }
    
    traverse $1
    

    usage:
    ./test.sh dir
    gives output:

    ./test.sh
    ./testA
      ./testA/dat2
      ./testA/dat1
      ./testA/testB
        ./testA/testB/dat4
    ./testC
      ./testC/dat3
    

提交回复
热议问题