简体   繁体   中英

Linux command to print a tree like directory structure

I'm trying to write a script which will print directories, subdirectories and their files in a tree structure, but without using tree command.

Example:

DIR: A 
     f1
     f2 
     DIR: B
          f3 
DIR: C
     file1
     file21

I have tried multiple of solutions, but I always ran into the problem that I could not distinguish between a directory or a file, therefore I could not apply the right formatting. The "DIR: " prefix makes it complicated. Is there something very obvious that I'm missing?

Use the the -d test:

if [ -d "$path" ] ; then
    echo DIR
fi

Cited from this SO question

Is this what your looking for tree , should be in most distributions (maybe as an optional install)?

~> tree -d /proc/self/
/proc/self/
|-- attr
|-- cwd -> /proc
|-- fd
|   `-- 3 -> /proc/15589/fd
|-- fdinfo
|-- net
|   |-- dev_snmp6
|   |-- netfilter
|   |-- rpc
|   |   |-- auth.rpcsec.context
|   |   |-- auth.rpcsec.init
|   |   |-- auth.unix.gid
|   |   |-- auth.unix.ip
|   |   |-- nfs4.idtoname
|   |   |-- nfs4.nametoid
|   |   |-- nfsd.export
|   |   `-- nfsd.fh
|   `-- stat
|-- root -> /
`-- task
    `-- 15589
        |-- attr
        |-- cwd -> /proc
        |-- fd
        | `-- 3 -> /proc/15589/task/15589/fd
        |-- fdinfo
        `-- root -> /

27 directories

sample taken from maintainers web page.

You can add the option -L # where # is replaced by a number, to specify the max recursivity level.

Remove -d to display also files.

您也可以尝试这些命令的变体

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

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

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

find -type d

tree -l

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM