7

I want to list the subdirectories of a directory using tree command. But I don't want to print indentation lines. I only want to have the whitespaces instead.

I couldn't find the correct parameter in man page. Maybe I can pipe the output of tree to sed to remove the lines.

Mert Nuhoglu
  • 661
  • 2
  • 7
  • 11

4 Answers4

8

So you want something like this:

tree | sed 's/├\|─\|│\|└/ /g'

It replaces all those "line" characters with spaces.


See:

$ tree
.
├── dir1
│   ├── file1
│   └── file2
└── dir2
    ├── file1
    └── file2

2 directories, 4 files
$ tree | sed 's/├\|─\|│\|└/ /g'
.
    dir1
        file1
        file2
    dir2
        file1
        file2

2 directories, 4 files
chaos
  • 47,463
  • 11
  • 118
  • 144
3

It works:

tree | sed -e 's/[├──└│]/ /g' 
smallyu
  • 31
  • 2
  • This looks very similar to [this answer](https://unix.stackexchange.com/a/245416/117549) by chaos; can you explain why yours is better? – Jeff Schaller Aug 19 '21 at 10:56
  • @JeffSchaller Because this one actually works, I guess. This replaces each character in the collection with a whitespace, while the one of chaos seems to replace something that doesn't even appear in `tree` output. – Philippos Aug 19 '21 at 15:52
  • Maybe the terminal representation changed, or something else changed in the intervening ... 5+ years. They just looked like very similar characters to me. Indeed, using my browser to search for each character, I find them matched between the answers. – Jeff Schaller Aug 19 '21 at 15:54
0

You can simply add the -i flag to your tree command to not display the indentations. A bit simpler than piping to sed!

guido
  • 8,481
  • 1
  • 20
  • 28
  • 2
    It looks like the author is trying to have each line of output prefixed by whitespace, rather than e.g. `├──` (though it's a bit ambiguously phrased). `-i` removes all prefixes, so you can't really tell what the tree structure is. – M. Justin Oct 04 '17 at 15:28
  • This removes the folder names as well. – Rishabh Deep Singh Aug 02 '20 at 00:44
0

Another (sed-free) way would be

tree | iconv -f utf8 -c -t latin1 | tr '\240' ' '

Here I convert the output from utf8 to latin1 (i.e. ISO-8859-1, ASCII would be also an option but I want to preserve some "Umlauts"). The -c option of iconv "silently discards characters that cannot be converted". Lastly, I remove non-breaking spaces. This might not be relevant to you.

Caveat: you loose UTF-8 encoded chars if they cannot be converted to your target encoding.

smartmic
  • 259
  • 1
  • 9