Показать дерево папок linux

Linux command to print directory structure in the form of a tree

Just run find . Or find . -not -path ‘*/\.*’ to hide files and folders starting with . . If you want to have output with spaces, as in the question, use it with this «find prettifier» script: find . -not -path ‘*/\.*’ | python -c «import sys as s;s.a=[];[setattr(s,’a’,list(filter(lambda p: c.startswith(p+’/’),s.a)))or (s.stdout.write(‘ ‘*len(s.a)+c[len(s.a[-1])+1 if s.a else 0:])or True) and s.a.append(c[:-1]) for c in s.stdin]»

The policy of closing questions without migrating is harmful to both stackoverflow and human knowledge in general. In the last 3 days, every single questions I googled and came across was closed for similar reasoning, and no more activity was able to happen. This means no one can update it, no one can give a better answer, and it makes stackoverflow look shortsighted or elitist. Stackoverflow should consider requiring a migration when a topic is found to have these conditions.

I agree with @NickYeates I am here in late September of 2017 still finding answers to this same question. Think long term when we design these question and answer policies!

11 Answers 11

Is this what you’re looking for tree? It should be in most distributions (maybe as an optional install).

~> tree -d /proc/self/ /proc/self/ |-- attr |-- cwd -> /proc |-- fd | `-- 3 -> /proc/15589/fd |-- fdinfo |-- net | |-- dev_snmp6 | |-- netfilter | |-- rpc | | |-- auth.rpcsec.context | | |-- auth.rpcsec.init | | |-- auth.unix.gid | | |-- auth.unix.ip | | |-- nfs4.idtoname | | |-- nfs4.nametoid | | |-- nfsd.export | | `-- nfsd.fh | `-- stat |-- root -> / `-- task `-- 15589 |-- attr |-- cwd -> /proc |-- fd | `-- 3 -> /proc/15589/task/15589/fd |-- fdinfo `-- root -> / 27 directories 

sample taken from maintainer’s web page.

Читайте также:  Rockstar games launcher linux

You can add the option -L # where # is replaced by a number, to specify the max recursion depth.

Remove -d to display also files.

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

It will show a graphical representation of the current sub-directories without files in a few seconds, e.g. in /var/cache/ :

 . |-apache2 |---mod_cache_disk |-apparmor |-apt |---archives |-----partial |-apt-xapian-index |---index.1 |-dbconfig-common |---backups |-debconf 

If you want it with spaces, more like the OP requested, then this: ls -R | grep «:$» | sed -e ‘s/:$//’ -e ‘s/[^-][^\/]*\// /g’ -e ‘s/^/ /’

@Ben thanks for that, all other (non- tree ) answers produce a result that does not look perfectly correct to me. For example in this answer, there should be a line going down from apt then horizontally to archives , instead it comes down from . and goes to archives , only because of more indentation you can guess that it’s actually a subfolder of apt . So you could as well just leave the lines away, it’s at least not misleading then.

This command works to display both folders and files.

. |-trace.pcap |-parent | |-chdir1 | | |-file1.txt | |-chdir2 | | |-file2.txt | | |-file3.sh |-tmp | |-json-c-0.11-4.el7_0.x86_64.rpm 

Source: Comment from @javasheriff here. Its submerged as a comment and posting it as answer helps users spot it easily.

for python3 I found find . |grep -vE ‘pyc|swp|__init’ | sed -e «s/[^-][^\/]*\// |/g» -e «s/|\([^ ]\)/|-\1/» working well

This was a great help as we didn’t have tree installed on a certain server. This will most likely work on any standard Linux system.

Since it was a successful comment, I am adding it as an answer:
To print the directory structure in the form of a tree,
WITH FILES

Читайте также:  Прошивка смартфона на linux

If you would like to sort your result list then combine the nice solution above with sort this way: find . | sort | sed -e «s/[^-][^\/]*\// |/g» -e «s/|\([^ ]\)/|-\1/»

To add Hassou’s solution to your .bashrc, try:

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

Nice alias. But there is missing ‘ ‘ (2 single quote chars) at the end. It works even without it, but. if you want to add some more commands at the end you will see the literal is not complete. So it should go alias lst=’ls -R | grep «:$» | sed -e ‘»‘»‘s/:$//'»‘»‘ -e ‘»‘»‘s/[^-][^\/]*\//—/g'»‘»‘ -e ‘»‘»‘s/^/ /'»‘»‘ -e ‘»‘»‘s/-/|/'»‘»»

Since I was not too happy with the output of other (non- tree ) answers (see my comment at Hassou’s answer), I tried to mimic tree s output a bit more.

It’s similar to the answer of Robert but the horizontal lines do not all start at the beginning, but where there are supposed to start. Had to use perl though, but in my case, on the system where I don’t have tree , perl is available.

ls -aR | grep ":$" | perl -pe 's/:$//;s/[^-][^\/]*\// /g;s/^ (\S)/└── \1/;s/(^ | (?= ))/│ /g;s/ (\S)/└── \1/' 
. └── fd └── net │ └── dev_snmp6 │ └── nfsfs │ └── rpc │ │ └── auth.unix.ip │ └── stat │ └── vlan └── ns └── task │ └── 1310 │ │ └── net │ │ │ └── dev_snmp6 │ │ │ └── rpc │ │ │ │ └── auth.unix.gid │ │ │ │ └── auth.unix.ip │ │ │ └── stat │ │ │ └── vlan │ │ └── ns 

Suggestions to avoid the superfluous vertical lines are welcome 🙂

Читайте также:  Arch linux vs linux lts

I still like Ben’s solution in the comment of Hassou’s answer very much, without the (not perfectly correct) lines it’s much cleaner. For my use case I additionally removed the global indentation and added the option to also ls hidden files, like so:

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

Output (shortened even more):

. fd net dev_snmp6 nfsfs rpc auth.unix.ip stat vlan ns 

Источник

Утилита tree — просмотр дерева директорий в командной строке

Обычно для просмотра списка файлов и директорий в командной строке Linux используется команда ls . В данной заметке мы рассмотрим, как выводить древовидный список файлов и директорий. Для этого мы воспользуемся утилитой/командной tree

Команда tree рекурсивно обходит все вложенные директории и файлы для выбранной директории и выводит информацию в удобном древовидном формате.

Установка утилиты tree

По умолчанию утилита tree не установлена в популярных дистрибутивах Linux.

Для установки в Ubuntu выполните в терминале команду:

Для установки в Fedora выполните команду:

Синтаксис команды tree

Команду tree можно использовать следующим образом:

Опции

У команды довольно много опций, остановимся только на некоторых из них:

Полный список опций команды tree можно получить, выполнив команду man tree

Примеры использования

Рассмотрим несколько примеров использования команды tree

Дерево текущей директории

Выведем дерево файлов в текущей директории. Выполняем команду tree без аргументов:

Команда tree

Вывод размеров файлов

Воспользуемся опцией -h , чтобы показать размеры файлов:

Команда tree с выводом размеров файлов

Вывод владельца и даты

Выведем размеры, владельца, группу и дату изменения:

Источник

Оцените статью
Adblock
detector