我有tree
一些目录结构的命令输出(在文本文件中)。它看起来像:
% cat tree.txt
.
├── grandpartest
│ └── partest
│ └── test
│ ├── empty-asciidoc-document.adoc
│ └── empty-asciidoc-document1.adoc
├── grandpartest2
│ └── partest2
│ └── test2
│ ├── empty-asciidoc-document.adoc
│ ├── empty-asciidoc-document1.adoc
│ └── empty-asciidoc-document2.adoc
├── grandpartest3
│ └── partest3
│ └── test3
│ ├── empty-asciidoc-document.adoc
│ ├── empty-asciidoc-document1.adoc
│ ├── empty-asciidoc-document2.adoc
│ └── empty-asciidoc-document3.adoc
└── tree.txt
9 directories, 10 files
有什么方法可以解析这些文本文件以创建类似的目录结构?
我知道我可以使用mkdir -p
并touch
创建这个目录结构。但我感兴趣的主要是解析文本文件以获取与这些命令一起使用的值。
更新1:
根据@muru 的要求
% cat tree-j.txt
[{"type":"directory","name": ".","contents":[
{"type":"directory","name":"grandpartest","contents":[
{"type":"directory","name":"partest","contents":[
{"type":"directory","name":"test","contents":[
{"type":"file","name":"empty-asciidoc-document.adoc"},
{"type":"file","name":"empty-asciidoc-document1.adoc"}
]}
]}
]},
{"type":"directory","name":"grandpartest2","contents":[
{"type":"directory","name":"partest2","contents":[
{"type":"directory","name":"test2","contents":[
{"type":"file","name":"empty-asciidoc-document.adoc"},
{"type":"file","name":"empty-asciidoc-document1.adoc"},
{"type":"file","name":"empty-asciidoc-document2.adoc"},
{"type":"directory","name":"Untitled Folder","contents":[
]}
]}
]}
]},
{"type":"directory","name":"grandpartest3","contents":[
{"type":"directory","name":"partest3","contents":[
{"type":"directory","name":"test3","contents":[
{"type":"file","name":"empty-asciidoc-document.adoc"},
{"type":"file","name":"empty-asciidoc-document1.adoc"},
{"type":"file","name":"empty-asciidoc-document2.adoc"},
{"type":"file","name":"empty-asciidoc-document3.adoc"}
]}
]}
]},
{"type":"file","name":"tree.txt"},
{"type":"file","name":"tree-j.txt"}
]},
{"type":"report","directories":10,"files":11}
]
% cat tree-j.txt | parse-tree
Traceback (most recent call last):
File "/home/blueray/_resources/dotfiles/python/parse-tree", line 18, in <module>
process(structure)
File "/home/blueray/_resources/dotfiles/python/parse-tree", line 10, in process
os.mkdir(entry["name"])
FileExistsError: [Errno 17] File exists: '.'
解析的通常输出
tree
很棘手 - 它不是某种标准形式,例如 CSV。像 JSON 这样的标准结构化格式会更好,因为您需要对每个条目至少编码两到三条信息(名称、类型和附加信息,如链接目标或目录条目,这些信息会因文件类型而异)。tree -J
确实提供了非常简单的 JSON 输出,您可以使用 Python(它是默认 Ubuntu 安装的一部分并在标准库中进行 JSON 处理)来处理它:这仅处理目录、常规文件和链接;您需要为其他文件类型添加条件(不确定如何
tree
处理块设备、字符设备等)。