使用bash或php获取文件夹层次结构


getting folder hierarchy with bash or php

我使用的是一台我不熟悉的linux机器,所以我想从它的文件夹结构中打印一个txt。我记得我写过一个在php中做类似事情的脚本,但找不到它

  • bash脚本
  • 现有的linux命令行
  • php脚本
 find . -type d > dirstructure.txt

然而,在一个典型的linux盒子上,我宁愿不从根目录运行它。如果你这样做并得到几个权限错误,你可以将错误发送到/dev/null

 find . -type d > dirstructure.txt 2> /dev/null

快速且肮脏:

class Crawl_directory
{
    public $exclude = array();
    public $paths = array();
    public $tree = FALSE;
    public $tree_str = FALSE;
    public function __construct($path, $exclude = array())
{
        if ( !$path || !is_dir($path) )
            return FALSE;
        $this->exclude = array_merge(array(), $exclude);
        $this->tree = $this->crawl($path);
        $this->tree_str = $this->create_tree($this->tree);
}
    public function crawl($path)
    {
        $arr = array();
        $items = scandir($path);
        $this->paths[] = $path;
        foreach ( $items as $k => $v ) {
            if ( !in_array($v, $this->exclude) && $v != '.' && $v != '..' ) {
                if ( is_dir($path.'/'.$v) ) {
                    $arr[$v] = $this->crawl($path.'/'.$v);
                } else {
                    $arr[$v] = '';
                }
            }
        }
        return $arr;
    }
    function create_tree($arr)
    {
        $out = '<ul>'."'n";
        foreach ( $arr as $k => $v ) {
            $out .= '<li class="'.((is_array($v)) ? 'folder' : 'file').'">'.$k.'</li>'."'n";
            if ( is_array($v) ) {
                $out .= $this->create_tree($v);
            }
        }
        $out .= '</ul>'."'n";
        return $out;    
    }
    function get_tree()
    {
        return $this->tree; 
        }
    function print_tree()
    {
        echo $this->tree_str;   
    }
}

试试这个?

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

取自http://www.centerkey.com/tree/