【问题标题】:Directory tree structure in shellshell中的目录树结构
【发布时间】:2014-05-01 04:00:55
【问题描述】:

我想使用 shell 命令打印一个目录树结构,谁能帮我知道怎么做?因为我有点新。

PS:我不能使用 Sed 和 Octs

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

【问题讨论】:

  • 欢迎来到 Stack Overflow。请尽快阅读About 页面。 [轻度调侃:在一个目录中包含多个文件,这些文件仅在名称末尾的尾随空格(或其他不可见字符)的数量上有所不同,这是一个坏主意。我看不出你怎么能把这么多Lorem's 放到一个目录中(除非你使用回车来覆盖不同的前缀,我想)。] 你应该展示你所拥有的例如,尝试过,或者您打算如何获取目录名称列表。
  • 这是一个unix/linux系统吗?如果是这样,请查看您的系统是否有ptree。阅读man ps 时,请寻找tree 选项。 (最好在您使用的操作系统类型的问题上包含一个标签)。祝你好运。
  • 是的,我正在寻找类似的东西,但是我不想使用诸如树之类的 prevues 编写代码,我不能使用 sed,我想了解步骤并知道我能做什么用于创建这样的树

标签: shell command


【解决方案1】:

这是一个递归解决方案,它不是最有效但原生的bash 并且易于理解:

$ cat tree.sh
#!/bin/bash

shopt -s nullglob

tree()
{
        if [ "$1" = '-d' ]; then
                _TREE_DIRSONLY=1
                shift
        fi
        _tree "${1-.}"
}

_tree()
{
        local indent="${indent}"
        local dir=${1%/}

        printf "%s|-- %s\n" "${indent}" "${dir##*/}"
        indent="${indent}  "
        for file in "$1"/*; do
                if [ -d "${file}" ]; then
                        _tree "${file}"
                        continue
                fi
                (( _TREE_DIRSONLY > 0 )) && continue
                printf "%s|-- %s\n" "${indent}" "${file##*/}"
        done
}

tree "$@"

.

$ ./tree.sh /proc/fs
|-- fs
  |-- cifs
    |-- cifsFYI
    |-- DebugData
    |-- LinuxExtensionsEnabled
    |-- LookupCacheEnabled
    |-- MultiuserMount
    |-- SecurityFlags
    |-- traceSMB
  |-- ext4
  |-- jbd2
  |-- nfsd
  |-- nfsfs
    |-- servers
    |-- volumes
  |-- xfs
    |-- stat
    |-- xqm
    |-- xqmstat

$ ./tree.sh -d /proc/fs
|-- fs
  |-- cifs
  |-- ext4
  |-- jbd2
  |-- nfsd
  |-- nfsfs
  |-- xfs

【讨论】:

  • 这也可以方便地添加到具有以下别名的 .bashrc 文件中 alias lst="tree . | less"
猜你喜欢
  • 2019-06-26
  • 2012-04-01
  • 1970-01-01
  • 2016-09-09
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
相关资源
最近更新 更多