Sorting files in linux

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

Источник

How to Find and Sort Files Based on Modification Date and Time in Linux

Usually, we are in habit of saving a lot of information in form of files on our system. Some, hidden files, some kept in a separate folder created for our ease of understanding, while some as it is. But, this whole stuff fills our directories; usually desktop, making it look like a mess. But, the problem arises when we need to search for a particular file modified on particular date and time in this huge collection.

Find and Sort Files by Date and Time in Linux

People comfortable with GUI’s can find it using File Manager, which lists files in long listing format, making it easy to figure out what we wanted, but those users having habit of black screens, or even anyone working on servers which are devoid of GUI’s would want a simple command or set of commands that could ease out their search.

Real beauty of Linux shows here, as Linux has a collection of commands which if used separately or together can help to search for a file, or sort a collection of files according to their name, date of modification, time of creation, or even any filter you could think of applying to get your result.

Here, we will unveil the real strength of Linux by examining a set of commands which can help sorting a file or even a list of files by Date and Time.

Linux Utilities to Sort Files in Linux

Some basic Linux command line utilities that are just sufficient for sorting a directory based on Date and Time are:

ls command

ls – Listing contents of directory, this utility can list the files and directories and can even list all the status information about them including: date and time of modification or access, permissions, size, owner, group etc.

We’ve already covered many articles on Linux ls command and sort command, you can find them below:

sort command

sort – This command can be used to sort the output of any search just by any field or any particular column of the field.

We’ve already covered two articles on Linux sort command, you can find them below:

These commands are in themselves very powerful commands to master if you work on black screens and have to deal with lots of files, just to get the one you want.

Some Ways to Sort Files using Date and Time

Below are the list of commands to sort based on Date and Time.

1. List Files Based on Modification Time

The below command lists files in long listing format, and sorts files based on modification time, newest first. To sort in reverse order, use ‘-r’ switch with this command.

2. List Files Based on Last Access Time

Listing of files in directory based on last access time, i.e. based on time the file was last accessed, not modified.

3. List Files Based on Last Modification Time

Listing of files in directory based on last modification time of file’s status information, or the ‘ctime’ . This command would list that file first whose any status information like: owner, group, permissions, size etc has been recently changed.

If ‘-a’ switch is used with above commands, they can list and sort even the hidden files in current directory, and ‘-r’ switch lists the output in reverse order.

For more in-depth sorting, like sorting on Output of find command, however ls can also be used, but there ‘sort’ proves more helpful as the output may not have only file name but any fields desired by user.

Below commands show usage of sort with find command to sort the list of files based on Date and Time.

To learn more about find command, follow this link: 35 Practical Examples of ‘find’ Command in Linux

4. Sorting Files based on Month

Here, we use find command to find all files in root (‘/’) directory and then print the result as: Month in which file was accessed and then filename. Of that complete result, here we list out top 11 entries.

The below command sorts the output using key as first field, specified by ‘-k1’ and then it sorts on Month as specified by ‘M’ ahead of it.

5. Sort Files Based on Date

Here, again we use find command to find all the files in root directory, but now we will print the result as: last date the file was accessed, last time the file was accessed and then filename. Of that we take out top 11 entries.

The below sort command first sorts on basis of last digit of the year, then sorts on basis of last digit of month in reverse order and finally sorts on basis of first field. Here, ‘1.8‘ means 8th column of first field and ‘n’ ahead of it means numerical sort, while ‘r’ indicates reverse order sorting.

6. Sorting Files Based on Time

Here, again we use find command to list out top 11 files in root directory and print the result in format: last time file was accessed and then filename.

The below command sorts the output based on first column of the first field of the output which is first digit of hour.

7. Sorting Ouptut of ls -l based on Date

This command sorts the output of ‘ls -l’ command based on 6th field month wise, then based on 7th field which is date, numerically.

Conclusion

Likewise, by having some knowledge of sort command, you can sort almost any listing based on any field and even its any column you desire. These were some of tricks to help you sort files based on Date or Time. You can have your own tricks build based on these. However, if you have any other interesting trick, you can always mention that in your comments.

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.

Источник

Sorting files in linux

Уделим немного времени знакомству с консольными утилитами 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»>

Источник

How to Sort Files in Linux using Sort Command

Sort command is helpful to sort/order lines in text files. You can sort the data in text file and display the output on the screen, or redirect it to a file. Based on your requirement, sort provides several command line options for sorting data in a text file.

Sort Command Syntax:

For example, here is a test file:

And, here is what you get when sort command is executed on this file without any option. It sorts lines in test file and displays sorted output.

1. Perform Numeric Sort using -n option

If we want to sort on numeric value, then we can use -n or –numeric-sort option.

Create the following test file for this example:

The following sort command sorts lines in test file on numeric value in first word of line and displays sorted output.

2. Sort Human Readable Numbers using -h option

If we want to sort on human readable numbers (e.g., 2K 1M 1G), then we can use -h or –human-numeric-sort option.

Create the following test file for this example:

The following sort command sorts human readable numbers (i.e 1K = 1 Thousand, 1M = 1 Million, 1G = 1 Giga, 1T = 1 Tera) in test file and displays sorted output.

3. Sort Months of an Year using -M option

If we want to sort in the order of months of year, then we can use -M or –month-sort option.

Create the following test file for this example:

The following sort command sorts lines in test file as per month order. Note, lines in file should contain at least 3 character name of month name at start of line (e.g. jan, feb, mar). If we will give, ja for January or au for August, then sort command would not consider it as month name.

4. Check if Content is Already Sorted using -c option

If we want to check data in text file is sorted or not, then we can use -c or –check, –check=diagnose-first option.

Create the following test file for this example:

The following sort command checks whether text file data is sorted or not. If it is not, then it shows first occurrence with line number and disordered value.

5. Reverse the Output and Check for Uniqueness using -r and -u options

If we want to get sorted output in reverse order, then we can use -r or –reverse option. If file contains duplicate lines, then to get unique lines in sorted output, “-u” option can be used.

Create the following test file for this example:

The following sort command sorts lines in test file in reverse order and displays sorted output.

The following sort command sorts lines in test file in reverse order and removes duplicate lines from sorted output.

6. Selectively Sort the Content, Customize delimiter, Write output to a file using -k, -t, -o options

If we want to sort on the column or word position in lines of text file, then “-k” option can be used. If we each word in each line of file is separated by delimiter except ‘space’, then we can specify delimiter using “-t” option. We can get sorted output in any specified output file (using “-o” option) instead of displaying output on standard output.

Create the following test file for this example:

The following sort command sorts lines in test file on the 3rd word of each line and displays sorted output.

Here, several options are used altogether. In test file, words in each line are separated by delimiter ‘|’. It sorts lines in test file on the 2nd word of each line on the basis of numeric value and stores sorted output into specified output file.

The contents of output file are shown below.

Источник

Читайте также:  Домашний каталог это linux
Оцените статью