List all directories recursively in a tree format

前端 未结 5 1911
春和景丽
春和景丽 2020-12-28 09:47

I want to simulate a tree command using Shell Script that displays all the directories recursively in this format:

.
|-- Lorem
|-- Lorem
|-- Lor         


        
相关标签:
5条回答
  • 2020-12-28 09:53

    Modifying sputnick's answer to get closer to your original format (which I prefer):

    find ./ -type d -print | sed -e 's;[^/]*/; /;g;s;/ ;    ;g;s;^ /$;.;;s; /;|-- ;g'
    

    The only difference now is the last line doesn't start with a backtick:

    .
    |-- Lorem
    |-- Lorem
    |-- Lorem
        |-- Lorem
        |-- Lorem
    |-- Lorem
    |-- Lorem
    

    with awk

    find . -type d -print 2>/dev/null | awk '!/\.$/ {for (i=1;i<NF-1;i++){printf("    ")}printf("|-- ")};{print $NF}' FS='/'
    
    0 讨论(0)
  • 2020-12-28 09:53

    ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^/]*//--/g' -e 's/^/ /' -e 's/-/|/'

    taken from here: http://www.centerkey.com/tree/

    0 讨论(0)
  • 2020-12-28 09:59

    You can just launch :

    tree .
    

    OR

    tree $absolute/path/of/your/dir
    

    If you want to display the hidden files.

    By default tree does not print hidden files (those beginning with a dot '.'), just type:

    tree -a .
    

    This is what tree command do.

    0 讨论(0)
  • 2020-12-28 10:03

    Modified base on the awk one from http://www.unix.com/shell-programming-scripting/50806-directory-tree.html

    pwd;find . -type d -print 2>/dev/null|awk '!/\.$/ {for (i=1;i<NF-1;i++){printf("│   ")}print "├── "$NF}'  FS='/'
    

    Output looks more similar to tree:

    /etc
    ├── sudoers.d
    ├── susehelp.d
    │   ├── htdig
    ├── sysconfig
    │   ├── SuSEfirewall2.d
    │   │   ├── services
    │   ├── network
    │   │   ├── if-down.d
    │   │   ├── if-up.d
    │   │   ├── providers
    │   │   ├── scripts
    │   ├── scripts
    ├── sysctl.d
    ├── systemd
    │   ├── system
    │   │   ├── default.target.wants
    │   │   ├── getty.target.wants
    │   │   ├── multi-user.target.wants
    
    0 讨论(0)
  • 2020-12-28 10:19

    Try doing this (not exactly the same output, but very close) :

    find ./ -type d -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
    

    From http://mlsamuelson.com/content/tree-approximation-using-find-and-sed

    with awk

    find . -type d -print 2>/dev/null|awk '!/\.$/ {for (i=1;i<NF;i++){d=length($i);if ( d < 5  && i != 1 )d=5;printf("%"d"s","|")}print "---"$NF}'  FS='/'
    

    See http://www.unix.com/shell-programming-scripting/50806-directory-tree.html

    0 讨论(0)
提交回复
热议问题