Linux размер папок с сортировкой

How to list the size of each file and directory and sort by descending size in Bash?

I found that there is no easy to get way the size of a directory in Bash? I want that when I type ls — , it can list of all the sum of the file size of directory recursively and files at the same time and sort by size order. Is that possible?

What exactly do you mean by the «size» of a directory? The number of files under it (recursively or not)? The sum of the sizes of the files under it (recursively or not)? The disk size of the directory itself? (A directory is implemented as a special file containing file names and other information.)

@KeithThompson @KitHo du command estimates file space usage so you cannot use it if you want to get the exact size.

@ztank1013: Depending on what you mean by «the exact size», du (at least the GNU coreutils version) probably has an option to provide the information.

12 Answers 12

Simply navigate to directory and run following command:

OR add -h for human readable sizes and -r to print bigger directories/files first.

du -a -h --max-depth=1 | sort -hr 

du -h requires sort -h too, to ensure that, say 981M sorts before 1.3G ; with sort -n only the numbers would be taken into account and they’d be the wrong way round.

This doesn’t list the size of the individual files within the current directory, only the size of its subdirectories and the total size of the current directory. How would you include individual files in the output as well (to answer OP’s question)?

@ErikTrautman to list the files also you need to add -a and use —all instead of —max-depth=1 like so du -a -h —all | sort -h

Apparently —max-depth option is not in Mac OS X’s version of the du command. You can use the following instead.

Unfortunately this does not show the files, but only the folder sizes. -a does not work with -d either.

To show files and folders, I combined 2 commands: l -hp | grep -v / && du -h -d 1 , which shows the normal file size from ls for files, but uses du for directories.

(this willnot show hidden (.dotfiles) files)

Use du -sm for Mb units etc. I always use

because the total line ( -c ) will end up at the bottom for obvious reasons 🙂

PS:

  • See comments for handling dotfiles
  • I frequently use e.g. ‘du -smc /home// | sort -n |tail’ to get a feel of where exactly the large bits are sitting

du —max-depth=1|sort -n or find . -mindepth 1 -maxdepth 1|xargs du -s|sort -n for including dotfiles too.

@arnaud576875 find . -mindepth 1 -maxdepth 1 -print0 | xargs -0 du -s | sort -n if some of the found paths could contain spaces.

This is a great variant to get a human readable view of the biggest: sudo du -smch * | sort -h | tail

Command

Output

3,5M asdf.6000.gz 3,4M asdf.4000.gz 3,2M asdf.2000.gz 2,5M xyz.PT.gz 136K xyz.6000.gz 116K xyz.6000p.gz 88K test.4000.gz 76K test.4000p.gz 44K test.2000.gz 8,0K desc.common.tcl 8,0K wer.2000p.gz 8,0K wer.2000.gz 4,0K ttree.3 

Explanation

  • du displays «disk usage»
  • h is for «human readable» (both, in sort and in du)
  • max-depth=0 means du will not show sizes of subfolders (remove that if you want to show all sizes of every file in every sub-, subsub-, . folder)
  • r is for «reverse» (biggest file first)
Читайте также:  Linux root mount options

ncdu

When I came to this question, I wanted to clean up my file system. The command line tool ncdu is way better suited to this task.

Just type ncdu [path] in the command line. After a few seconds for analyzing the path, you will see something like this:

$ ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help --- / --------------------------------------------------------- . 96,1 GiB [##########] /home . 17,7 GiB [# ] /usr . 4,5 GiB [ ] /var 1,1 GiB [ ] /lib 732,1 MiB [ ] /opt . 275,6 MiB [ ] /boot 198,0 MiB [ ] /storage . 153,5 MiB [ ] /run . 16,6 MiB [ ] /etc 13,5 MiB [ ] /bin 11,3 MiB [ ] /sbin . 8,8 MiB [ ] /tmp . 2,2 MiB [ ] /dev ! 16,0 KiB [ ] /lost+found 8,0 KiB [ ] /media 8,0 KiB [ ] /snap 4,0 KiB [ ] /lib64 e 4,0 KiB [ ] /srv ! 4,0 KiB [ ] /root e 4,0 KiB [ ] /mnt e 4,0 KiB [ ] /cdrom . 0,0 B [ ] /proc . 0,0 B [ ] /sys @ 0,0 B [ ] initrd.img.old @ 0,0 B [ ] initrd.img @ 0,0 B [ ] vmlinuz.old @ 0,0 B [ ] vmlinuz 

Delete the currently highlighted element with d , exit with CTRL + c

ls -S sorts by size. Then, to show the size too, ls -lS gives a long ( -l ), sorted by size ( -S ) display. I usually add -h too, to make things easier to read, so, ls -lhS .

Ah, sorry, that was not clear from your post. You want du , seems someone has posted it. @sehe: Depends on your definition of real — it is showing the amount of space the directory is using to store itself. (It’s just not also adding in the size of the subentries.) It’s not a random number, and it’s not always 4KiB.

find . -mindepth 1 -maxdepth 1 -type d | parallel du -s | sort -n 

I think I might have figured out what you want to do. This will give a sorted list of all the files and all the directories, sorted by file size and size of the content in the directories.

(find . -depth 1 -type f -exec ls -s <> \;; find . -depth 1 -type d -exec du -s <> \;) | sort -n 

[enhanced version]
This is going to be much faster and precise than the initial version below and will output the sum of all the file size of current directory:

echo `find . -type f -exec stat -c %s <> \; | tr '\n' '+' | sed 's/+$//g'` | bc 

the stat -c %s command on a file will return its size in bytes. The tr command here is used to overcome xargs command limitations (apparently piping to xargs is splitting results on more lines, breaking the logic of my command). Hence tr is taking care of replacing line feed with + (plus) sign. sed has the only goal to remove the last + sign from the resulting string to avoid complains from the final bc (basic calculator) command that, as usual, does the math.

Performances: I tested it on several directories and over ~150.000 files top (the current number of files of my fedora 15 box) having what I believe it is an amazing result:

# time echo `find / -type f -exec stat -c %s <> \; | tr '\n' '+' | sed 's/+$//g'` | bc 12671767700 real 2m19.164s user 0m2.039s sys 0m14.850s 

Just in case you want to make a comparison with the du -sb / command, it will output an estimated disk usage in bytes ( -b option)

Читайте также:  Linux опции команды find

As I was expecting it is a little larger than my command calculation because the du utility returns allocated space of each file and not the actual consumed space.

[initial version]
You cannot use du command if you need to know the exact sum size of your folder because (as per man page citation) du estimates file space usage. Hence it will lead you to a wrong result, an approximation (maybe close to the sum size but most likely greater than the actual size you are looking for).

I think there might be different ways to answer your question but this is mine:

ls -l $(find . -type f | xargs) | cut -d" " -f5 | xargs | sed 's/\ /+/g'| bc 

It finds all files under . directory (change . with whatever directory you like), also hidden files are included and (using xargs ) outputs their names in a single line, then produces a detailed list using ls -l . This (sometimes) huge output is piped towards cut command and only the fifth field ( -f5 ), which is the file size in bytes is taken and again piped against xargs which produces again a single line of sizes separated by blanks. Now take place a sed magic which replaces each blank space with a plus ( + ) sign and finally bc (basic calculator) does the math.

It might need additional tuning and you may have ls command complaining about arguments list too long.

Источник

Размеры папок и дисков в Linux. Команды df и du

Для просмотра свободного и занятого места на разделах диска в Linux можно воспользоваться командой df.

Первым делом можно просто ввести команду df без каких-либо аргументов и получить занятое и свободное место на дисках. Но по умолчанию вывод команды не очень наглядный — например, размеры выводятся в КБайтах (1К-блоках).

Примечание:

df не отображает информацию о не смонтированных дисках.

Опция -h

Опция -h (или —human-readable) позволяет сделать вывод более наглядным. Размеры выводятся теперь в ГБайтах.

Размер конкретного диска

Команде df можно указать путь до точки монтирования диска, размер которого вы хотите вывести:

Размер папок на диске (du)

Для просмотра размеров папок на диске используется команда du. Если просто ввести команду без каких либо аргументов, то она рекурсивно проскандирует вашу текущую директорию и выведет размеры всех файлов в ней. Обычно для du указывают путь до папки, которую вы хотите проанализировать. Если нужно просмотреть размеры без рекурсивного обхода всех папок, то используется опция -s (—summarize). Также как и с df, добавим опцию -h (—human-readable).

Просмотр размера текущей папки

Чтобы показать объем просто одного текущего каталога (со всеми вложенными файлами + подкаталогами) подойдёт команда du с ключиком -sh.

Вот пример, как определить размер директории данного сайта:

Посмотреть размеры всех папок

Если нужно посчитать вес всех директорий плюс файлы — добавляем звёздочку:

Отобразить размеры всех вложенных папок

Чтобы проверить информацию в том числе вообще по всем папкам, вместе со вложенными — понадобится самый короткий вариант:

Внимание: если такой случайно запустить в корне на объёмном диске с большим количеством информации — лучше сразу жмите CTRL-C, т.к. во-первых, иначе придётся сильно подождать 😉 , во-вторых, десятки-сотни экранов информации будут бессмысленными. Потому эта простая команда должна использоваться лишь для, соответственно, простых случаев.

Отсортировать папки по объёму

Покажет объём в килобайтах с сортировкой — самые большие папки/файлы сверху. Если нужно в мегабайтах:

К сожалению более удобный ключик h («human» — автовыбор кило-мега-гига) в данном случае (du -sh *| sort -nr) не подойдёт, т.к. сортировка идёт по «числам» (не учитывая, что это KB/MB/GB). Для этого придётся использовать длинную команду:

du -s *|sort -nr|cut -f 2-|while read a;do du -hs $a;done

Источник

Читайте также:  Generate password list linux

How do you sort du output by size?

How do you sort du -sh /dir/* by size? I read one site that said use | sort -n but that’s obviously not right. Here’s an example that is wrong.

[~]# du -sh /var/* | sort -n 0 /var/mail 1.2M /var/www 1.8M /var/tmp 1.9G /var/named 2.9M /var/run 4.1G /var/log 8.0K /var/account 8.0K /var/crash 8.0K /var/cvs 8.0K /var/games 8.0K /var/local 8.0K /var/nis 8.0K /var/opt 8.0K /var/preserve 8.0K /var/racoon 12K /var/aquota.user 12K /var/portsentry 16K /var/ftp 16K /var/quota.user 20K /var/yp 24K /var/db 28K /var/empty 32K /var/lock 84K /var/profiles 224M /var/netenberg 235M /var/cpanel 245M /var/cache 620M /var/lib 748K /var/spool 

The accepted answer sort -h worked for me in Ubuntu 16.04 LTS in Aug 2017. First I find my mounted drive by cd /mnt (mounted by UUID in fstab). Then I do du >~/dumnt.out then sort -h ~/dumnt.out >~/dumntsort.out then I can do `tail ~/dumntsort.out to see the largest space hogs.

18 Answers 18

If you have GNU coreutils (common in most Linux distributions), you can use

The -h option tells sort that the input is the human-readable format (number with unit; 1024-based so that 1023 is considered less than 1K which happens to match what GNU du -h does).

Note:

If you are using an older version of Mac OSX, you need to install coreutils with brew install coreutils , then use gsort as drop-in replacement of sort .

Newer versions of macOS (verified on Mojave) support sort -h natively.

On OSX you can install coreutils via brew and add the bin folder to your PATH into your rc file, and -h should be available.

Try using the -k flag to count 1K blocks intead of using human-readable. Then, you have a common unit and can easily do a numeric sort.

You don’t explictly require human units, but if you did, then there are a bunch of ways to do it. Many seem to use the 1K block technique above, and then make a second call to du.

If you want to see the KB units added, use:

du -k | sed -e 's_^\(6*\)_\1 KB_' | sort -n 

If you don’t have a recent version of GNU coreutils, you can call du without -h to get sortable output, and produce human-friendly output with a little postprocessing. This has the advantage of working even if your version of du doesn’t have the -h flag.

du -k | sort -n | awk ' function human(x) < if (x<1000) else s="kMGTEPZY"; while (x>=1000 && length(s)>1) return int(x+0.5) substr(s,1,1) > ' 

If you want SI suffixes (i.e. multiples of 1000 rather than 1024), change 1024 to 1000 in the while loop body. (Note that that 1000 in the condition is intended, so that you get e.g. 1M rather than 1000k .)

If your du has an option to display sizes in bytes (e.g. -b or -B 1 — note that this may have the side effect of counting actual file sizes rather than disk usage), add a space to the beginning of s (i.e. s=» kMGTEPYZ»; ), or add if (x <1000) else at the beginning of the human function.

Displaying a decimal digit for numbers in the range 1–10 is left as an exercise to the reader.

Источник

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