Linux file size sort

Содержание
  1. Linux ls Command Sort Files By Size
  2. The default output (sort by alphabetically)
  3. Linux force sort by size option
  4. Sort output and print sizes in human readable format (e.g., 1K 234M 2G)
  5. Sorting ls command output by file size on Linux
  6. ls Command Sort Files By Size Command Options
  7. How to exclude directories when all files ordered by size
  8. Conclusion
  9. Как отсортировать файлы по размеру с помощью команды ls в Linux
  10. 1) Перечислить содержимое содержимого каталога при сортировке по размеру
  11. 2) Список содержимого каталога с сортировкой по размеру
  12. 3) Сортировка выходных данных и размеров в удобном формате для чтения (например, 1K 48M 1G)
  13. Бонусные советы
  14. 4) Список в алфавитном порядке сортировки
  15. 5) Список в обратном порядке по алфавиту
  16. 6) Список скрытого содержимого каталога в алфавитном порядке сортировки
  17. 7) Список содержимого каталога в алфавитном порядке сортировки
  18. How to List All Files Ordered by Size in Linux
  19. If You Appreciate What We Do Here On TecMint, You Should Consider:
  20. Linux file size sort
  21. Использование утилиты ls в linux
  22. Использование утилиты du в linux
  23. Использование утилиты sort в linux
  24. Linux Sort by Size
  25. Introduction to Linux Sort by Size
  26. How Linux Sort by Size Command works?

Linux ls Command Sort Files By Size

H ow do I sort all *.avi or *.py files in $HOME/Download/ directory by file size using Linux ls command line utility? How do I list all files ordered by size in Linux using ls command?

The ls command is used to list directory contents under Linux and Unix like operating systems. If no options or operands are given, the contents of the current directory are displayed on the screen. By default entries are sorted alphabetically if none of the -cftuvSUX nor —sort option passed to the ls command. Let us see how to use the ls command to sort files by size on Linux and Unix-like systems such as FreeBSD.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements GNU ls/BSD ls
Est. reading time 4 mintues

The default output (sort by alphabetically)

Type the following command:
$ ls
$ ls *.py
$ ls *.avi

Fig.01: ls Command Output

Linux force sort by size option

You need to pass the -S or —sort=size option as follows to Linux or Unix command line:
$ ls -S
$ ls -S -l
$ ls —sort=size -l
$ ls —sort=size *.avi
$ ls -S -l *.avi
Sample outputs:

Fig.02: Sort files / folders (directories) by size

You will see largest file first before sorting the operands in lexicographical order. The following command will sort file size in reverse order:
$ ls -l -S | sort -k 5 -n
OR try (see comments below, thanks!):
$ ls -lSr

Fig.03: Ls Command Sort By Size in Reverse (Lowest First) Order

Sort output and print sizes in human readable format (e.g., 1K 234M 2G)

Pass the -h option to the ls command as follows:
$ ls -lSh
$ ls -l -S -h *.avi
$ ls -l -S -h

Sorting ls command output by file size on Linux

Run the following ls command:
ls -Slh
OR
ls -Slhr

ls Command Sort Files By Size Command Options

Table 1: ls command options to list all files ordered by size
Option Description
-l Long listing
-S Sort by file size, largest first
—sort=size sort by size instead of file name(s)
-r Reverse order while sorting
-h Human readable output. with -l and -s option, print sizes like 1K 234M 2G etc.

How to exclude directories when all files ordered by size

Try filtering outputs of ls command using grep command:
ls -lS | grep -v ‘^d’
ls -Slh | grep -v ‘^d’
ls -Slhr | grep -v ‘^d’

One can use find command as well along with sort command to just list dir size in sorted order:
find . -type d -ls | sort -n -r
Or just list files and exclude all dirs when sorting:
find . -type f -ls | sort -n -r

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Conclusion

This page showed how to list all files ordered by size in Linux or Unix like systems. See ls(1) command man page for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Как отсортировать файлы по размеру с помощью команды ls в Linux

Если вы новый пользователь в мире Linux, команда ls является самой популярной и очень полезной командой для перечисления содержимого каталогов.

В этой статье мы объясним, как использовать параметр сортировки ls для отображения содержимого каталога по размеру.

1) Перечислить содержимое содержимого каталога при сортировке по размеру

Чтобы перечислить содержимое определенного каталога с сортировкой по размеру, мы будем использовать опции -lS с командой ls.

Чтобы указать размер файла, мы будем использовать параметр -s с командой ls.

2) Список содержимого каталога с сортировкой по размеру

Чтобы перечислить содержимое определенного каталога с сортировкой по размеру, мы будем использовать опции -lSr с командой ls.

3) Сортировка выходных данных и размеров в удобном формате для чтения (например, 1K 48M 1G)

для сортировки выходных данных и размеров в человекочитаемом формате мы будем использовать -h с командой ls.

Кроме того, мы можем выводить размеры в читаемом формате для конкретного расширения.

Бонусные советы

4) Список в алфавитном порядке сортировки

Чтобы перечислить содержимое определенного каталога с сортировкой по алфавиту, мы будем использовать команду ls только без опции, потому что по умолчанию используется алфавитная сортировка.

Чтобы перечислить содержимое определенного каталога с подробной информацией, добавьте путь к каталогу.

5) Список в обратном порядке по алфавиту

Чтобы перечислить содержимое определенного каталога с подробными сведениями в обратном порядке сортировки по алфавиту, мы будем использовать опции -lr с командой ls.

6) Список скрытого содержимого каталога в алфавитном порядке сортировки

Чтобы отобразить скрытое содержимое определенного каталога, мы будем использовать опции -a или -all с командой ls.

7) Список содержимого каталога в алфавитном порядке сортировки

Чтобы показать содержимое определенного каталога с подробными сведениями, такими как права доступа к файлам, количество ссылок, имя владельца и владельца группы, размер файла, время последней модификации и имя файла / каталога, мы будем использовать -l с командой ls.

Источник

How to List All Files Ordered by Size in Linux

In one of our several articles about listing files using the popular ls command, we covered how to list and sort files by last modification time (date and time) in Linux. In this short handy article, we will present a number of useful ls command options to list all of the files in a certain directory and sort them by file size in Linux.

To list all files in a directory, open a terminal window and run the following command. Note that when ls invoked without any arguments, it will list the files in the current working directory.

In the following command the -l flag means long listing and -a tells ls to list all files including (.) or hidden files. To avoid showing the . and .. files, use the -A option instead of -a .

List All Files in Linux

To list all files and sort them by size, use the -S option. By default, it displays output in descending order (biggest to smallest in size).

List All Files Sort By Sizes

You can output the file sizes in human-readable format by adding the -h option as shown.

List Files Sort By Sizes in Linux

And to sort in reverse order, add the -r flag as follows.

List All Files Sort By Sizes in Reverse Order

Besides, you can list subdirectories recursively using the -R option.

List Sub-directories Recursively

You will also find the following related articles useful:

If you any other way to list the files ordered by sizes in Linux, do share with us or do you have questions or thoughts to share about this guide? If yes, reach us via the feedback form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Linux file size sort

Уделим немного времени знакомству с консольными утилитами ls, du и sort в ОС Linux. Рассмотрим их использование с основными ключами и в различных комбинациях, для сортировки файлов и директорий (папок) по размеру.

Использование утилиты ls в linux

1. Вывод списка файлов и директории.

Данный вывод неинформативен поэтому лучше использовать ls вместе с ключами.

2. Вывод списока файлов и директорий, включая скрытые файлы в виде «расширеного списка».

«-l» — выводит расширеный листинг.

«-h» — выводит размер файлов в удобном для чтения формате (GB/MB/KB).

«-a» — выводит все файлы, в том числе и «скрытые».

Стоит отметить, что «ls» не может вычислять размер директорий, поэтому, для вывода размера директорий / каталогов / папок будем использовать утилиту «du».

Использование утилиты du в linux

1. Вывод списка директории c вложенными директориями.

По-умолчанию «du» выводит размер, не только каждой директории, но и всех вложенных в нее директорий /каталогов / папок.

2. Вывод списка директории без вложенных директорий.

3. Вывод списка директории c одним уровнем вложения.

«—max-depth=1» — задает уровень вложенности директорий равной 1.

«-h» — выводит размер файлов в удобном для чтения формате (GB/MB/KB).

Использование утилиты sort в linux

1. Вывод папок отсортированных по размеру.

«-n» — сортировка по числам.

«-r» — отображает в выводе самые большие числа вначале.

2. Вывод директорий / каталогов / папок отсортированных по размеру в мегабайтах.

3. Вывод директорий / каталогов / папок и файлов отсортированных по размеру.

4. Вывод директорий и файлов отсортированных по размеру и преведенный к удобному виду для восприятия размера (KB/MB/GB).

Самый сложный, но в тоже время самый информативный и красивый вывод.

5. Вывод директорий /каталогов / папок и файлов отсортированных по размеру в файл.

Данный вариант может быть полезен, например в случае очень большошо количества строк в выводе.

На этом все. Существует еще множество различных вариантов сортировки, так что предлагайте свои. Комментируем, подписываемся ну и всем пока:)

1″ :pagination=»pagination» :callback=»loadData» :options=»paginationOptions»>

Источник

Linux Sort by Size

By Priya Pedamkar

Introduction to Linux Sort by Size

In the Linux operating system, we are using the “sort” for sorting the multiple files in a specific order. We can sort the files in terms of size, name, etc. While sorting the normal files, the sorting is based on the ASCII format. If we need to sort the files in terms of size, we can use the kilobyte, megabyte, gigabyte, etc. The sort command help to identify the large size files on the Linux environment. It will be really helpful to clean the unwanted large file and keep the environment healthy. The Linux sort utility was written by Mike Haertel and Paul Eggert.

Syntax of Sort Command:

Web development, programming languages, Software testing & others

sort [OPTION]. [FILE].
sort [OPTION]. —files0-from=F

  • sort: We can use the “sort” keyword in the syntax or command. It will take different arguments like OPTION, file name, path, etc. As per the provided arguments, it will sort the necessary files as per the giving parameters or options.
  • OPTION: We can provide the different flags as the option that is compatible with the “sort” command.
  • FILE: We can provide the specific file or path to the “sort” command. It will help to identify the files as per the given parameters.

How Linux Sort by Size Command works?

In the Linux operating system, it is mandatory to check the files and folders size. If the size will increase and we haven’t taken the necessary action on it. The server or the environment will be in an unhealthy state or may the server will not work. To avoid such incidents, we can use the sort command-line utility to identify the large size files and folders.

The sort command will accept the different arguments like the option, file, file path, etc. As per the arguments, the sort command will sort the files as per the file size.

Below are the lists of options that are compatible in sort command as per the file size.

Источник

Читайте также:  Дизайн папок для windows
Оцените статью