Сортировка файлов в командной оболочке Linux
Ищете новый способ организации своих файлов и выполнения над ними каких-либо операций? Тем, кто работает с компьютерами, часто надо что-то отсортировать. Например, список файлов. Сортировка файлов с помощью Bash-команд sort и ls поможет вам навести порядок в своих материалах. Здесь мы поговорим об основах сортировки файлов и их содержимого в Linux.
Предварительные требования
Тут, при разборе примеров, используется Ubuntu 20.04, но вам, для того чтобы попробовать то, о чём мы будем говорить, подойдёт любой дистрибутив Linux.
Алфавитная сортировка файлов
Существует множество способов сортировки файлов в Linux. Предлагаю начать с самого распространённого способа — с сортировки файлов по алфавиту.
Запустите терминал и выполните команду ls -l , показанную ниже, чтобы получить список файлов, находящихся в директории, отсортированных по имени в восходящем порядке. Флаг -l сообщает команде ls о том, что ей нужно вывести данные в виде списка, содержащего подробные сведения о файлах.
Алфавитная сортировка файлов
Команда ls по умолчанию выводит файлы с сортировкой их по алфавиту в восходящем порядке. Для того чтобы обратить порядок сортировки — нужно передать этой команде флаг -r . Например, это может выглядеть как ls -lr . Передача флага -r команде ls возможна и в примерах, рассмотренных ниже.
Сортировка файлов по размеру
Вместо того чтобы сортировать файлы по алфавиту, вам может понадобиться отсортировать их по размеру. Это может быть нужно, например, когда надо найти самые большие или самые маленькие файлы.
Для того чтобы отсортировать файлы по размеру — команде ls надо передать флаг -S .
Вот команда, которая позволяет отсортировать файлы по размеру и вывести список файлов с их подробным описанием.
Эта команда, как показано ниже, выведет список файлов, отсортированных от больших файлов к меньшим. Для того чтобы обратить порядок сортировки — воспользуйтесь флагом -r . Выглядеть это может как ls -lSr .
Сортировка файлов по размеру
Сортировка файлов по времени их модификации
Возможно, вам понадобится отсортировать файлы по времени их модификации. Например, вы забыли имя созданного файла, но помните время, когда его создавали.
Для сортировки файлов по времени модификации команде ls можно передать параметр -t .
Сортировка файлов по времени модификации
Сортировка файлов по расширению
Если вам нужен файл определённого типа, в деле по его поиску вам может очень хорошо помочь сортировка файлов по расширению.
Тут нам снова пригодится команда ls . На этот раз — с флагом -X .
Сортировка файлов по расширению
Обратите внимание на то, что эта команда, выводя группу файлов с одним и тем же расширением, сортирует файлы в пределах этой группы по именам в восходящем порядке.
Сортировка содержимого текстового файла
Теперь вы уже знаете немало способов сортировки файлов. Поэтому давайте переключим внимание с команды ls на команду sort . Эта команда позволяет сортировать содержимое файлов, руководствуясь переданными ей флагами. Правда, прежде чем опробовать эту команду, нам понадобится файл, содержимое которого мы будем сортировать.
Выполните следующую команду, для того чтобы создать файл с именем fruits.txt , содержащий названия фруктов. Флаг -e позволяет интерпретировать обратную косую черту в конструкции \n , благодаря чему каждое слово будет идти с новой строки.
Теперь выполните следующую команду, для того чтобы отсортировать слова в этом файле.
Ниже показано содержимое файла, отсортированное по алфавиту в восходящем порядке.
Сортировка содержимого файла по алфавиту в восходящем порядке
Команда sort , без флагов, сортирует содержимое файлов в восходящем порядке. Для того чтобы обратить порядок сортировки — воспользуйтесь флагом -r . Соответствующая команда может выглядеть как sort -r fruits.txt . Сортировка данных в обратном порядке с применением -r может быть выполнена и в других рассмотренных тут примерах применения sort .
Сортировка списка чисел в текстовом файле
Для сортировки списков чисел в файлах используется та же команда sort , но — с флагом -n . Чтобы опробовать это на практике — создадим файл scores.txt , в каждой строке которого будет одно число, выбранное мной случайным образом. Вот команда для создания такого файла:
Теперь, чтобы отсортировать числа в этом файле, выполним следующую команду.
Сортировка чисел в файле
Видно, что числа, находящиеся в файле, отсортированы от самого маленького к самому большому.
Сортировка списка номеров версий программы в текстовом файле
Возможно, у вас есть файл с номерами версий программы, содержимое которого вы хотите отсортировать. Для того чтобы это сделать — нам понадобится всё та же команда sort , но теперь — с опцией —version-sort .
Создадим, как обычно, файл, на котором будем экспериментировать. Это будет versions.txt , в каждой строке которого имеется номер версии.
Теперь выполним команду такого вида:
Здесь имеется новая опция — —field-separator , которая сообщает команде sort о том, что части каждого из номеров разделены точкой. В качестве разделителя полей можно указать любой символ, который разделяет поля номеров версий, хранящиеся в файле.
Сортировка номеров версий в файле
Поиск файлов с заданным расширением и их сортировка
В предыдущих примерах мы решали наши задачи с помощью запуска какой-то одной команды ( ls или sort ). Но при работе в Linux часто возникает необходимость совместного использования двух или большего количества команд. Как это сделать? Сделать это можно с помощью конвейера команд, перенаправляющего выходные данные одной команды на вход другой команды.
Следующая конструкция позволит найти (команда find ) все markdown-файлы ( -iname «*.md» ) в рабочей директории ( . ) и отсортировать их по алфавиту в нисходящем порядке ( sort -r ). Попробуйте поискать и посортировать другие файлы, меняя расширение «*.md» на какое-то другое.
Поиск и вывод нужных файлов с сортировкой их по алфавиту в нисходящем порядке
Если вам удобнее сохранить то, что получится, в файл, а не выводить в консоль, воспользуйтесь опцией —output команды sort . В результате, например, может получиться такая конструкция: find . -iname «*.md» | sort -r —output=sorted.txt . В данном случае отсортированный список найденных файлов попадёт в файл sorted.txt .
Итоги
Я написал эту статью для того, чтобы показать всем желающим различные возможности по сортировке файлов с помощью Bash-команд в Linux. Теперь вы знаете о том, как сортировать списки файлов и то, что содержится в файлах. Вы теперь умеете создавать конвейеры из команд для выполнения более сложных операций сортировки файлов. И, кстати, обладая этими знаниями, вы вполне можете написать скрипты, которые автоматизируют задачи сортировки файлов и содержимого файлов.
How can I sort all files by size in a directory?
How can I display the files in a unix directory sorted by their human readable size, going from largest to smallest?
but it does not seem to work.
7 Answers 7
If you have the appropriate sort version you may simply use:
ls -S wasn’t an option on the OS for me. The following worked:
ls -l | sort -k 5nr
They «key» was to specify the column to sort (get it, the «key»). Above I’m specifying -k 5nr meaning sort on 5th column which is size (5) evaluated as a number (n) in descending order (n)
Reference sort documentation for more information
du : estimate file disk usage.
sort : sort lines of text.
man du; man sort for more. It works for me on ubuntu v15.
I got this to work for me:
Which (I just figured-out) is the same as:
Unlike ls -S , this will properly handle sparse files:
-
The Overflow Blog
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.6.16.43501
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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: 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.
Sr No | Option | Description |
1 | -b, –ignore-leading-blanks | It will help to ignore the leading blanks. |
2 | -d, –dictionary-order | It will only consider the blanks and alphanumeric characters. |
3 | -f, –ignore-case | It will help to convert the lower case to upper case characters. |
4 | -g, –general-numeric-sort | It will help to compare the general numerical value. |
5 | -i, –ignore-nonprinting | It will only consider the printable characters. |
6 | -M, –month-sort | It will help to compare the month parameters like [ compare (unknown) < ‘JAN’ < … < ‘DEC’ ]. |
7 | -h, –human-numeric-sort | It will help to compare the human readable numbers like 2K 1G. |
8 | -n, –numeric-sort | It will help to compare the string numerical value. |
9 | -R, –random-sort | It will help to sort by the random hash of keys. |
10 | –random-source=FILE | The parameters help to get the random bytes from FILE. |
11 | -r, –reverse | It will help to reverse the result of comparisons. |
12 | –sort=WORD | It will help for sort according to the WORD but we need to use the specific flags with it like general-numeric -g, human-numeric -h, month -M, numeric -n, random -R, version -V. |
13 | -V, –version-sort | It is the natural sort of (version) numbers within the text. |
Examples of Linux Sort by Size
Given below are the examples mentioned :
Example #1
Sort Command – Sort Big File
The sort command, we are able to sort the largest file size in the environment. It is the most common way to practice the sort command in the Linux operating system. We need to use the “-r and -n” option with the sort command.
Code:
Explanation:
- As per the above command, we are using the sort command with different options like “-n & -r”. We are sorting the files that are in big size on the “/” location and printing only the first 3 largest files.
Output:
Example #2
Sort Command – Sort File in Working Directory
In the sort command, we are having the functionality to sort the largest file in the current working directory.
Code:
Explanation:
- In sort command, we can sort the file in the current working directory and print the first 3 largest files. The current working directory is “/home”.
Output:
Example #3
Sort Command – Sort with File Size
In the Sort Command, we can search out the number of files. From the same files, we can sort the size of the files in human-readable format like K, M, G. We can use the “-r” option for the recursive search.
Code:
Explanation:
- In the above sort command, we are able to find the top 3 files those are in big size. In the first screenshot, we are having the number of files in “/home” directory. As per the above sort command, we are able to find the top 3 files those are big in size refer to second screenshot.
Output:
Example #4
Sort Command – With Find Option
In the Linux environment, we are having the functionality to sort the file as per the file name as well as the file size. But we can also use the sort command with the combination of different Linux commands like find.
Code:
Explanation:
- As per the above command, we are using the sort command with the combination of the find command. We are finding the top three large files in “/home” directory.
Output:
Conclusion
We have seen the uncut concept of “Linux Sort by Size” with the proper example, explanation and command with different outputs. The Sort Command will help to sort the multiple files in terms of size and string. We can use the sort command with the multiple commands like du, find, etc.
Recommended Articles
We hope that this EDUCBA information on “Linux Sort by Size” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How to Sort Files by Size in Linux Command Line
Learn to sort files by their size using the ls command in the Linux terminal. Also learn about finding the biggest files.
The ls command is used for displaying the contents of a directory. Use the option -l and you can list the files and directories along with their attributes.
Size is one of the attributes displayed by the ls -l command. Though you can see the sizes of the file, they are displayed alphabetically.
If you want to find the biggest or smallest files in the current working directory, you can sort the files by size.
The -S option of the ls command sorts the files by size.
However, you’ll be more comfortable combining it with the options -h and -l:
Why? I’ll share it in detail with examples.
Sort files by size
There is a sort command in Linux. But it is used for sorting the content of files, not the files themselves.
You can display files in the current directory in the long listing format so that you can see their size:
To sort files by size, use the option -S with the ls command. Mind it, it’s capital S for sorting.
That’s good but you can make it better by adding the -h option. This option makes the output of the ls command displays the file size in human readable formats.
This means now you can see files ordered by size in KB, MB, or GB.
List files by their size in reverse order
By default, it is sorted to put bigger files on the top. You can reverse the order and display the bigger files at the bottom. Put the reverse option -r with the rest.
This is particularly useful when you have numerous files (like log files) in a directory and you want to see the biggest ones. Instead of scrolling back, you can see the bigger files right on the screen.
Get the 10 biggest files in a directory
The best thing about the Linux command line is that you can combine various commands and get a different result.
Let’s say you want to see some of the largest files in the current directory. Sort the files by size and then use the pipe redirection with the head command.
In the example, I used 11 because the first line shows the total number of blocks used in the directory.
You can use the tail command with reversed sorting but that’s too redundant, I think.
Everything is done in the current working directory. If you want to do it system-wide, you can start at / but then you need to use root privileges. But ls command is not suitable in such cases. Instead, use the find command to look for files bigger than a certain size.
Include hidden files while sorting files by size
If you add . (dot) at the beginning of a file or directory name, it is hidden from the normal listing views in the ls command. These are called hidden files.
Many configuration files are hidden from the normal views. While sorting for files by size, you should take these hidden files into consideration as well.
Option -a shows the hidden files including the special . and .. directories:
Note the .member.csv file in the output:
Recursively sort files by size
So far you only dealt with files in the current directory. But what about the files in the sub directories?
If you are looking for the largest file in the current location, you should also consider looking for files in the sub directories.
You can use the option -R of the ls command to list files in the sub directories.
However, this is not the correct approach because it doesn’t sort all the files together, They are sorted in their respective directories.
Alternatively, you can use the du command and combine it to recursively sort files based on their size:
Conclusion
Now you know how to use the ls command to sort files based on their size. I hope you learned a few other things along the way.