
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a File In-Place in Linux
In order to be able to sort the contents of a file in Linux, we must first be aware of the sort command that Linux provides us with.
The sort command is mainly used to sort the contents of a file. It arranges the records in a particular manner. By default, these records are sorted considering the fact that they are ASCII based values.
Few key points to remember about the sort command are −
SORT command does the sorting from one line to another, one line at a time.
It prints the contents of the file when used on a file, in the exact same manner like the cat command does.
It normally ignores case sensitivity.
Syntax
sort filename
Now that we know a little about the sort command, let’s make use of it. Consider the few examples shown below.
Example 1
The file before sorting has the contents in this order.
immukul@192 d1 % cat somefile.txt Is this text added this file contains a new text stream and i am going to edit that stream yes i can do that ask jeffrey
Command
sort filename.txt
Output
immukul@192 d1 % sort somefile.txt Is this text added a new text stream and i am going to edit ask jeffrey that stream this file contains yes i can do that
As we can see the output is sorted based on the ASCII encoding.
It should be noted that the output is surely sorted, but the contents of the file won’t be changed at all, and we can confirm this by printing the contents of the file again with the help of the cat command.
immukul@192 d1 % cat somefile.txt Is this text added this file contains a new text stream and i am going to edit that stream yes i can do that ask jeffrey
In order to actually change the contents of the file you can make use of the command shown below.
sort somefile.txt > anotherfile.txt
Output
immukul@192 d1 % cat anotherfile.txt Is this text added a new text stream and i am going to edit ask jeffrey that stream this file contains yes i can do that