Linux ls tree view

How to list all the files in a tree (a directory and its subdirs)?

For a task of mine I need to list all the files in a tree (a directory, all its subdirs, all subdirs of those, etc.). I’d prefer to see them in Nautilus or Krusader, but a command-line solution is interesting as well (in this case I will need files full names, sizes and modification times to be listed).

This question has an awful lot of views. Perhaps you could accept the answer you found most helpful, to save others some time @Ivan?

10 Answers 10

tree will be very convenient for you.

using tree filepath to list the files.

That’s probably the simplest method. I’m just hacking out a find script to give you a touch more control.

find /path/ -printf "%TY-%Tm-%Td\t%s\t%p\n" 

You can play with the printf formatting as much as you like. This gives you a great opportunity to get things formatted the way you need them, which is invaluable if you’re using the output in another application.

For better readability, you can pipe it all through the column command and it will automagically resize things so they line up.

find /path/ -printf "%TY-%Tm-%Td\t%s\t%p\n" | column -t 

ls is the standard command to list files in Ubuntu and other Linux and Unix operating systems. ls is particularly useful to learn because you will find it installed on every Unix system you ever meet. By default running this displays only the files in the current directory.

However the -R ‘flag’ is the recursive option (note the capital R, not r) which will show you all the sub-directories as well.

You asked for «details» too — for this you want the -l flag (that’s a lowercase L, not the number one). Be aware this gives you file permissions information as well as file size, time/date info and file name.

If you want to also show hidden files/folders (the equivalent of Ctrl + H in Nautilus) then add the -a ‘all’ flag.

You can merge flags together, to give you something like:

If you run this on any decent sized folder you will find this produces a huge long output that scrolls down your screen very fast. To get around this, you can ‘pipe’ the output of ls through a program called less (the name is a parody of the similar more which was around first but has more features).

This will allow you to use the up/down arrow keys, alongside PageUp/Down to go through the output at a more comfortable speed.

Источник

How to List Files Recursively in Linux command line

Want to list files recursively and see the contents of all the subdirectories in Linux? Here’s how you can do that.

The ls command is the default for viewing the contents of a directory. This is despite the existence of the dedicated dir command.

Читайте также:  Efi boot linux windows

The ls command list the contents of the present directory, but it doesn’t show the contents of the subdirectories by default. You can make it though.

Use ls command to list files recursively

You can change the default behavior of the ls command to list files recursively by using the -R option.

list files in linux recursively

As you can see, it shows the contents of every subdirectory one by one.

That’s uppercase R . the lowercase r is used for the reverse display of ls output.

But wait, you can’t expect Linux to have just one solution. Here are some other ways of listing files recursively.

Use the tree command to list files recursively

By far, this is my favorite utility when it comes to listing files recursively as it gets the output in the easiest way possible.

But it does not come pre-installed in most distributions. If you’re on a Debian-based distro, you can use this command for installation:

Once you are done with the installation, you just have to append the filename with the tree command:

use the tree command to list files recursively in linux

Use the find command to list files recursively

You’ll find me often praising the find command being so extensive with more than 50 options and can also be used for listing files recursively.

You can recursively search sub-directories with the -ls option of the find command. It will list all the files but not the hidden files. It will show additional information such as read-write permissions:

how to use find command to print files recursively in linux

Similarly, you can also use the -print option with the find command if you just want to list files recursively:

find Directory_name -print

use the find command to list files recursively

Use the du command to list files recursively

The du command is used to show the storage size of files and when used with the -a option, it will count and print the files recursively.

But I’m also going to use the -c option that will sum the total number of files available in the specified directory:

use the du command to list files recursively in linux

Wrapping Up

This was my take on how you can print files recursively in Linux. But you can do more with those utilities with enough knowledge.

And we have a detailed guide on how you can make the most out of man pages in Linux so you can be creative whenever you want!

Источник

How to print the directory tree in terminal

enter image description here

What is the command that can be used to draw the directory tree inside the terminal emulator?

3 Answers 3

You can use tree to print the directory tree in terminal. Install tree from terminal,

To see the directory tree, use

Or navigate to a directory and just use

It has some advanced options too. You can see owner’s username , groupname , date of last modification of a file/folder and so on using tree . It supports directory colors of ls so you can see colourized outputs.

You can do it easily with the following command:

find . -type d | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/| - \1/" 

This command will search recursively for directories inside the parent directory, and then draw the tree of the directories found.

You may also try the following to include all of the files as well.

@AvinashRaj Buddy the overall of the command is clear if you wan to learn more about sed please refer to some tutorials or google it. It’s really hard to explain all sed here!

Читайте также:  Файловая система linux manjaro

Maythux, you’re right that if you understand sed then your script is clear, but don’t be fooled into thinking sed/regexes are anything but a cryptic language you’ve learned over the years. It’s hardly intuitive — which I think is the spirit of Avinash Raj’s comment.

Источник

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.

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

Читайте также:  Установка pulseaudio astra linux

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

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 🙂

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