Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort a file in-place in Linux?
In Linux, the sort command is a powerful utility for arranging file contents in a specific order. By default, it sorts lines alphabetically based on ASCII values. However, the basic sort command only displays sorted output without modifying the original file. To sort a file in-place (modifying the original file), we need specific techniques.
Understanding the Sort Command
The sort command operates line by line, treating each line as a record. Key characteristics include −
Sorts one line at a time from the input
Displays file contents similar to the
catcommand when applied to filesCase-insensitive by default (though this can be changed with options)
Does not modify the original file unless explicitly redirected
Basic Syntax
sort filename
Example − Basic Sort Operation
Consider a file with unsorted content −
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
Using the basic sort command −
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
Important: The original file remains unchanged. This can be verified by running cat somefile.txt again.
Methods for In-Place Sorting
Method 1: Using the -o Option
The most straightforward way to sort a file in-place is using the -o option −
sort -o somefile.txt somefile.txt
This command safely sorts the file and writes the result back to the same file.
Method 2: Using Temporary Files
Create a sorted copy and replace the original −
sort somefile.txt > temp_sorted.txt && mv temp_sorted.txt somefile.txt
Method 3: Using Command Substitution
sort somefile.txt | sponge somefile.txt
Note: The sponge command (from moreutils package) reads input completely before writing output.
Common Sort Options
| Option | Description | Example |
|---|---|---|
| -r | Reverse sort order | sort -r -o file.txt file.txt |
| -n | Numerical sort | sort -n -o numbers.txt numbers.txt |
| -f | Case-insensitive | sort -f -o file.txt file.txt |
| -u | Remove duplicates | sort -u -o file.txt file.txt |
Verification Example
After sorting in-place with sort -o somefile.txt somefile.txt −
cat 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
The file content is now permanently sorted.
Conclusion
To sort a file in-place in Linux, use sort -o filename filename as the safest method. This approach ensures the original file is modified with sorted content while maintaining data integrity. Alternative methods include temporary files or specialized tools like sponge for more complex scenarios.
