sort files by depth (bash)

后端 未结 5 2196
半阙折子戏
半阙折子戏 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:24

    The simplest solution:

    $ echo * */* */*/* */*/*/* */*/*/*/* */*/*/*/*/*
    a a/b a/b/c a/b/c/d1 a/b/c/d2 a/b/c/d1/e a/b/c/d2/e a/b/c/d1/e/f a/b/c/d2/e/f
    

    Or, in column:

    $ echo * */* */*/* */*/*/* */*/*/*/* */*/*/*/*/* |tr ' ' '\n'
    a
    a/b
    a/b/c
    a/b/c/d1
    a/b/c/d2
    a/b/c/d1/e
    a/b/c/d2/e
    a/b/c/d1/e/f
    a/b/c/d2/e/f
    

    The depth of the tree is hardcoded in the example, but you can write a small script and make it more flexible:

    A="*"
    while true
    do
      B=$(echo $A)
      [ "$B" = "$A" ] && break
      echo $B
      A="$A/*"
    done | tr ' ' '\n'
    

    Example of usage:

    $ A="*"; while true; do B=$(echo $A); [ "$B" = "$A" ] && break; echo $B; A="$A/*"; done | tr ' ' '\n'
    a
    a/b
    a/b/c
    a/b/c/d1
    a/b/c/d2
    a/b/c/d1/e
    a/b/c/d2/e
    a/b/c/d1/e/f
    a/b/c/d2/e/f
    

    Examples are provided for the tree:

    $ mkdir -p a/b/c/d{1,2}/e/f
    $ tree .
    .
    └── a
        └── b
            └── c
                ├── d1
                │   └── e
                │       └── f
                └── d2
                    └── e
                        └── f
    
    9 directories, 0 files
    

    Find/depth solutions will obviously not work because find will shows subtrees one after another. The -depth key says in which direction subtree must be shown. But that doesn't mean, of course, that the output will be sorted by depth.

    $ find .
    .
    ./a
    ./a/b
    ./a/b/c
    ./a/b/c/d2
    ./a/b/c/d2/e
    ./a/b/c/d2/e/f
    ./a/b/c/d1
    ./a/b/c/d1/e
    ./a/b/c/d1/e/f
    
    $ find . -depth
    ./a/b/c/d2/e/f
    ./a/b/c/d2/e
    ./a/b/c/d2
    ./a/b/c/d1/e/f
    ./a/b/c/d1/e
    ./a/b/c/d1
    ./a/b/c
    ./a/b
    ./a
    .
    

    As you can see the answer is incorrect in both cases (with and without -find).

提交回复
热议问题