How to Use the Sort Command in Linux [10 Easy Ways]

Written by

Reviewed by

Last updated: July 2, 2024

Expert verified

SVG Image

TL;DR

To effectively use the sort command in Linux, you can use these methods:

  1. Sorting Lines of Text: sort filename.txt to sort the lines in ascending order, or sort -r filename.txt to sort in descending order.
  2. Sorting Numerical Data: sort -n filename.txt to sort the numerical values in ascending order, or sort -n -r filename.txt to sort in descending order.
  3. Sorting Fields within a Line: sort -k 2 filename.txt to sort by the second field, or sort -k 2 -r filename.txt to sort in descending order.
  4. Sorting Files: sort filename.txt to sort the contents of a single file, or sort file1.txt file2.txt file3.txt to sort multiple files.

Read the guide below to learn different methods to use the sort command in Linux and best practices to follow when using the command.

Managing data can quickly become overwhelming, especially with large lists or complex files. If you often need to sort data in Linux, youโ€™re in the right place. This post will show you how to use the sort command to organize your data efficiently. Youโ€™ll learn what the sort command is, why sorting is important, and various methods to sort text, numerical data, and fields within a line. By the end, youโ€™ll streamline your data management in Linux with ease.

What is the Sort Command?

The sort command in Linux helps you arrange the lines in a text file in a specific order. By default, it sorts lines alphabetically. However, you can also sort by numbers, months, or other criteria using different options.

For example, if you have a list of names in a file, the sort command can arrange them alphabetically from A to Z.

Importance of Sorting Data in Linux

Sorting data is important because it helps you organize and make sense of large amounts of information. Here are a few reasons why sorting is useful:

  • Easier Data Analysis: Sorted data is easier to analyze and understand. For example, a sorted list of sales figures can help you quickly identify trends.
  • Efficient Searching: When data is sorted, searching for specific items becomes faster and more efficient.
  • Better Presentation: Sorted data looks more professional and is easier to present in reports or documents.
  • Simplified Data Management: Sorting can help you manage files and records more effectively, making tasks like identifying duplicates or finding specific entries simpler.

How to Use the Sort Command in Linux

To use the sort command in Linux, open your terminal and type sort filename.txt to sort the lines of the file alphabetically. For numerical sorting, use sort -n filename.txt, and for reverse order, use sort -r filename.txt. To sort by a specific column, use sort -k column_number filename.txt. You can also combine options, like sort -n -r filename.txt for a reverse numerical sort. This command helps you efficiently organize data in text files.

Keep reading the guide below for 10 different methods to use the sort command in Linux:

1. Sorting Lines of Text

Sorting lines of text is one of the most common use cases for the sort command. Whether you’re organizing a list of names, sorting log entries, or alphabetizing text, the sort command simplifies the process. Follow these steps to sort lines in Linux:

  1. Open your Terminal.
opening terminal
  1. Navigate to the directory containing the file you want to sort.
navigating to directory 1
  1. Use the following command to sort the lines in ascending order: 
sort filename.txt
  1. This command will alphabetically sort the lines in the file.
sorting line of file in ascending order
  1. To sort in descending order, add the -r flag:
sort -r filename.txt
  1. This command will sort the lines from Z to A in reverse order.
sorting lines of file in descending order

2. Sorting Numerical Data

Sorting numerical data accurately is crucial for various tasks such as financial analysis or statistical computations. The sort command comes to the rescue, allowing you to sort numerical values effortlessly. Follow these steps to sort numerical data using the sort command:

  1. Access your Terminal window and navigate to the directory containing the file with numerical data.
  2. Use the following command to sort the numerical values in ascending order: 
sort -n filename.txt
  1. This command will sort the numbers in ascending order, from the smallest to the largest.
sorting numerical values in ascending order
  1. To sort in descending order, combine the -n and -r flags: 
sort -n -r filename.txt.
  1. This command will sort the numbers in reverse order, from the largest to the smallest.
sorting numerical values in descending order

3. Sorting Fields within a Line

When working with structured data containing fields, such as CSV files, sorting based on specific fields becomes necessary. The sort command allows you to sort data within lines using the -k option. Follow these steps to sort fields within a line using the sort command:

  1. Launch your command prompt.
  2. Use the -k option to specify the field you want to sort by. For example, to sort by the second field, use: 
sort -k 2 filename.txt
  1. This command will sort the lines based on the values in the specified field.
sorting content of file base on the second field

4. Sorting Files

The sort command is not limited to sorting individual lines or fields. It can sort entire files, making it a handy tool for organizing large datasets. You can seamlessly arrange their contents in the desired order by executing the sort command on one or multiple files. Follow these steps to sort files using the sort command:

  1. Enter the command window and navigate to the directory.
  2. To sort multiple files, run the following command: 
sort file1.txt file2.txt file3.txt
  1. This command will sort the lines within each file individually.
sorting multiple files at a time
  1. Redirect the sorted output to a new file using the > symbol: 
sort filename.txt > sorted.txt
  1. The command will save the sorted output in another file.
saving output to other file

5. Reversing the Sort Order

Sometimes you need to sort data in descending order, such as when viewing the latest entries first.

  1. Open your terminal.
  2. Create or open a text file you want to sort.
$ cat fruits.txt
viewing a text file in a terminal
  1. Run the sort command with the -r flag:
$ sort -r fruits.txt

This command will sort the lines in the file fruits.txt in reverse alphabetical order.

sorting lines in reverse alphabetic order

6. Sorting by Month

Sorting dates by month is useful when organizing logs or records with month names.

  1. Access your command window and open a text file with month names.
$ cat months.txt
viewing a file having months name
  1. Run the sort command with the -M flag:
$ sort -M months.txt

This command will sort the lines in months.txt according to calendar month order.

sorting the names in calendar month order

    7. Sorting and Removing Duplicates

    Often, you need to sort data and ensure that no duplicate entries exist.

    1. Launch your Terminal and access a text file with potential duplicate entries.
    $ cat fruits.txt
    viewing file having duplicate entries
    1. Run the sort command with the -u flag:
    $ sort -u fruits.txt

    This command will sort the lines in fruits.txt and remove any duplicate entries.

    sorting file and removing duplicate entries

      8. Case-Insensitive Sorting

      Sorting in a case-insensitive manner is useful when you want to ignore letter case differences in the sort order.

      1. Open your terminal.
      2. Open a text file with mixed-case entries.
      $ cat fruits.txt
      viewing a file having mix case entries
      1. Run the sort command with the -f flag:
      $ sort -f fruits.txt

      This command will sort the lines in fruits.txt without considering case differences.

      sorting files while ignoring case differences

      9. Sorting by Version Number

      Sorting version numbers is crucial when handling software versions or similar data.

      1. Access your Terminal and open a text file with version numbers.
      $ cat versions.txt
      viewing versions text file
      1. Run the sort command with the -V flag:
      $ sort -V versions.txt

      This command will sort the lines in versions.txt based on version numbers, taking into account the numerical value of each version component.

      sorting versions text file

      10. Sorting with Human-Readable Numbers

      This method is handy when sorting files with human-readable sizes (e.g., 1K, 1M, 1G).

      1. Open a text file with human-readable sizes.
      $ cat sizes.txt
      viewing a file containing sizes
      1. Run the sort command with the -h flag:
      $ sort -h sizes.txt

      This command will sort the lines in sizes.txt considering the human-readable sizes in the appropriate order.

      sorting sizes in an appropriate order

      Best Practices for Using the Sort Command

      Using the sort command effectively can save time and make data management easier. Here are six best practices to help you get the most out of this powerful Linux tool:

      • ๐Ÿ“‚ Always Keep Original Files Intact: Before sorting, make a copy of the original file. This prevents data loss and allows you to revert to the original if needed.
      • ๐Ÿ” Use the Correct Options: Familiarize yourself with different sort options, like -n for numeric sorting or -r for reverse order. Using the right option ensures accurate results.
      • ๐Ÿ—‚๏ธ Sort Large Files Efficiently: When working with large files, use the -S option to specify buffer size and the -T option for temporary directories. This speeds up the sorting process.
      • ๐Ÿ“… Handle Dates Properly: For sorting dates, use the appropriate options like -M for month names. Ensure date formats are consistent to avoid errors.
      • ๐Ÿ†” Remove Duplicates: Combine sort with the -u option to remove duplicate lines while sorting. This is especially useful for cleaning up data.
      • ๐Ÿค– Automate with Scripts: Use the sort command in shell scripts to automate regular sorting tasks. This improves efficiency and ensures consistency in your data management.

      In Conclusion

      In this article, I have explored various methods to use the sort command in Linux, including sorting text lines, numerical data, fields within lines, and entire files. I have also covered best practices to ensure efficient and accurate sorting, such as keeping original files intact, using the correct options, and automating with scripts.

      For further learning, I suggest:

      • Discover how to compare two files in Linux. This skill helps you easily identify differences between file versions, ensuring your data remains consistent and accurate.
      • Learn to use the ls command to sort files by size. Gaining this knowledge will give you better control over file management, making it simpler to locate and organize files efficiently.
      • Explore how to use the help command in Linux. Mastering this command will enhance your ability to quickly find information about any command, boosting your overall efficiency with the command line.

      Frequently Asked Questions

      How can I sort a file in reverse order?

      To sort a file in reverse order, simply add the -r flag to the sort command. This flag instructs the command to reverse the order of the sorted output, providing the desired result. For example, if you have a file named data.txt and want to sort it in reverse order, you can use the following command: sort -r data.txt. The sort command will then display the sorted output in reverse order on the Terminal.

      Does the sort command modify the original file?

      No, by default, the sort command does not modify the original file. It operates on the input file and displays the sorted output on the Terminal without altering the original file’s contents. This ensures that the original data remains intact. If you wish to save the sorted output to a new file, you can use redirection to redirect the output to a new file, like this: sort data.txt > sorted_data.txt. Alternatively, you can use the -o option followed by the desired filename to overwrite the original file with the sorted output: sort data.txt -o data.txt.

      Can the sort command handle files with varying line lengths?

      Yes, the sort command is designed to handle files with varying line lengths efficiently. It automatically detects and adjusts the sorting algorithm based on the data within each line, ensuring accurate sorting regardless of line length. Whether your file contains lines of different lengths or lines with uniform lengths, the sort command will process them appropriately. It analyzes the content of each line rather than relying on fixed line lengths. This flexibility allows the sort command to handle diverse datasets and sort them accurately based on the specified sorting criteria.

      Ojash

      Author

      Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

      Akshat

      Reviewer

      Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, heโ€™s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

      Share this article
      Shareable URL
      Prev Post

      How to Empty Log File Linux [6 Effective Methods]

      Next Post

      How to Install OpenSSH on Ubuntu and Enable It [15 Easy Steps]

      Leave a Reply

      Your email address will not be published. Required fields are marked *

      Read next