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.
4 Answers 4
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
-
2This
sed
expression does not appear to work in Mac OS X.M. Justin– M. Justin2017年10月04日 15:33:05 +00:00Commented Oct 4, 2017 at 15:33 -
Doesn't works for me as wellRishabh Deep Singh– Rishabh Deep Singh2020年08月02日 00:44:27 +00:00Commented Aug 2, 2020 at 0:44
-
Was this meant to be extended regular expressions? Then it shiould be
sed -E
, but still the graphical characters seem wrong.Philippos– Philippos2021年08月19日 15:49:15 +00:00Commented Aug 19, 2021 at 15:49
It works:
tree | sed -e 's/[├──└│]/ /g'
-
This looks very similar to this answer by chaos; can you explain why yours is better?2021年08月19日 10:56:54 +00:00Commented Aug 19, 2021 at 10:56
-
1@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– Philippos2021年08月19日 15:52:38 +00:00Commented Aug 19, 2021 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.2021年08月19日 15:54:28 +00:00Commented Aug 19, 2021 at 15:54
You can simply add the -i
flag to your tree
command to not display the indentations. A bit simpler than piping to sed!
-
3It 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– M. Justin2017年10月04日 15:28:22 +00:00Commented Oct 4, 2017 at 15:28 -
This removes the folder names as well.Rishabh Deep Singh– Rishabh Deep Singh2020年08月02日 00:44:58 +00:00Commented Aug 2, 2020 at 0:44
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.