Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a `find` like output to a `tree` like output

This question is a generalized version of the Output of ZipArchive() in tree format question.


Just before I am wasting time on writing this (*nix command line) utility, it will be a good idea to find out if someone already wrote it. I would like a utility that will get as its' standard input a list such as the one returned by find(1) and will output something similar to the one by tree(1)

E.g.:

Input:

/fruit/apple/green
/fruit/apple/red
/fruit/apple/yellow
/fruit/banana/green
/fruit/banana/yellow
/fruit/orange/green
/fruit/orange/orange
/i_want_my_mommy
/person/men/bob
/person/men/david
/person/women/eve

Output

/
|-- fruit/
|   |-- apple/
|   |   |-- green
|   |   |-- red
|   |   `-- yellow
|   |-- banana/
|   |   |-- green
|   |   `-- yellow
|   `-- orange/
|       |-- green
|       `-- orange
|-- i_want_my_mommy
`-- person/
    |-- men/
    |   |-- bob
    |   `-- david
    `-- women/
        `-- eve

Usage should be something like:

list2tree --delimiter="/" < Input > Output

Edit0: It seems that I was not clear about the purpose of this exercise. I like the output of tree, but I want it for arbitrary input. It might not be part of any file system name-space.

Edit1: Fixed person branch on the output. Thanks, @Alnitak.

like image 438
Chen Levy Avatar asked Dec 12 '10 08:12

Chen Levy


2 Answers

In my Debian 10 I have tree v1.8.0. It supports --fromfile.

--fromfile
Reads a directory listing from a file rather than the file-system. Paths provided on the command line are files to read from rather than directories to search. The dot (.) directory indicates that tree should read paths from standard input.

This way I can feed tree with output from find:

find /foo | tree -d --fromfile .

Problems:

  • If tree reads /foo/whatever or foo/whatever then foo will be reported as a subdirectory of .. Similarly with ./whatever: . will be reported as an additional level named . under the top level .. So the results may not entirely meet your formal expectations, there will always be a top level . entry. It will be there even if find finds nothing or throws an error.

  • Filenames with newlines will confuse tree. Using find -print0 is not an option because there is no corresponding switch for tree.

like image 95
Kamil Maciorowski Avatar answered Oct 07 '22 23:10

Kamil Maciorowski


An other tool is treeify written in Rust.

Assuming you have Rust installed get it with:

$ cargo install treeify
like image 41
Chen Levy Avatar answered Oct 08 '22 00:10

Chen Levy