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

时间:2012-08-30 17:32:24

标签: php linux bash

我正在使用我不熟悉的linux机器,因此我想从其文件夹结构中获取txt打印。我记得写过一个脚本,它在php中做了类似的事情,却找不到它。我正在寻找可以帮助我完成这项任务的以下任何一项:

  • bash脚本
  • 现有的linux命令行
  • 一个php脚本

3 个答案:

答案 0 :(得分:4)

 find . -type d > dirstructure.txt

但是,在典型的Linux机器上,我宁愿不从目录root运行它。如果您这样做并获得了一些权限错误,则可以将错误发送到/dev/null

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

答案 1 :(得分:1)

又快又脏:

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;   
    }
}

答案 2 :(得分:0)

试试这个?

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

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