Bash Script to Sort Lines in a File Easily
Use the Bash command
sort filename to sort lines in a file alphabetically, or write a script with sort inputfile -o outputfile to save sorted lines.Examples
Inputbanana
apple
cherry
Outputapple
banana
cherry
Inputdog
cat
bird
ant
Outputant
bird
cat
dog
Input
Output
How to Think About It
To sort lines in a file, think of reading each line and arranging them in order from A to Z. The Bash
sort command does this automatically by comparing lines and putting them in sequence.Algorithm
1
Get the filename as input.2
Read all lines from the file.3
Compare lines alphabetically.4
Arrange lines in ascending order.5
Output the sorted lines to the screen or save to a file.Code
bash
#!/bin/bash # Script to sort lines in a file input_file="$1" output_file="$2" if [[ ! -f "$input_file" ]]; then echo "File not found: $input_file" exit 1 fi sort "$input_file" -o "$output_file" echo "Sorted lines saved to $output_file"
Output
Sorted lines saved to sorted.txt
Dry Run
Let's trace sorting the file with lines: dog, cat, bird, ant
1
Check if input file exists
Input file 'animals.txt' exists.
2
Sort lines
Lines before sort: dog, cat, bird, ant Lines after sort: ant, bird, cat, dog
3
Save output
Sorted lines saved to 'sorted.txt'
| Original Line | Sorted Position |
|---|---|
| dog | 4 |
| cat | 3 |
| bird | 2 |
| ant | 1 |
Why This Works
Step 1: Using the sort command
The sort command reads all lines and compares them alphabetically.
Step 2: Saving sorted output
Using -o outputfile writes the sorted lines back to a file instead of printing to screen.
Alternative Approaches
Sort and print to screen
bash
#!/bin/bash input_file="$1" if [[ ! -f "$input_file" ]]; then echo "File not found" exit 1 fi sort "$input_file"
This prints sorted lines to the terminal without saving.
Sort with unique lines
bash
#!/bin/bash input_file="$1" if [[ ! -f "$input_file" ]]; then echo "File not found" exit 1 fi sort -u "$input_file" -o "$input_file"
Sorts and removes duplicate lines, saving back to the same file.
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting lines requires comparing them, which takes O(n log n) time where n is the number of lines.
Space Complexity
The sort command may use extra memory proportional to the number of lines to hold them during sorting.
Which Approach is Fastest?
Using the built-in sort command is fastest and most efficient compared to manual sorting in scripts.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sort command with -o | O(n log n) | O(n) | Saving sorted lines to a file |
| sort command printing to screen | O(n log n) | O(n) | Quick sorting without saving |
| sort -u for unique lines | O(n log n) | O(n) | Sorting and removing duplicates |
Use
sort -r to sort lines in reverse order.Forgetting to check if the input file exists before sorting causes errors.