PowerShell Script to Sort Lines in a File
Use
Get-Content 'input.txt' | Sort-Object | Set-Content 'output.txt' to read lines from a file, sort them alphabetically, and save the result to another file.Examples
Inputbanana
apple
carrot
Outputapple
banana
carrot
Inputdog
cat
bird
ant
Outputant
bird
cat
dog
Input
Output
How to Think About It
To sort lines in a file, first read all lines into memory, then arrange them in alphabetical order using a sorting method, and finally write the sorted lines back to a file.
Algorithm
1
Read all lines from the input file.2
Sort the lines alphabetically.3
Write the sorted lines to the output file.Code
powershell
Get-Content 'input.txt' | Sort-Object | Set-Content 'output.txt' Write-Output "Lines sorted and saved to output.txt"
Output
Lines sorted and saved to output.txt
Dry Run
Let's trace sorting the lines 'banana', 'apple', 'carrot' through the code
1
Read lines
Lines read: ['banana', 'apple', 'carrot']
2
Sort lines
Sorted lines: ['apple', 'banana', 'carrot']
3
Write lines
Sorted lines saved to output.txt
| Step | Lines |
|---|---|
| Read | banana, apple, carrot |
| Sort | apple, banana, carrot |
| Write | apple, banana, carrot |
Why This Works
Step 1: Reading the file
The Get-Content command reads all lines from the file into an array.
Step 2: Sorting the lines
The Sort-Object command sorts the array alphabetically by default.
Step 3: Saving the sorted lines
The Set-Content command writes the sorted lines back to a file.
Alternative Approaches
Using Out-File instead of Set-Content
powershell
Get-Content 'input.txt' | Sort-Object | Out-File 'output.txt' Write-Output "Sorted lines saved with Out-File"
Out-File adds default encoding and may add a newline at the end; Set-Content is simpler for plain text.
Sorting lines in-place
powershell
$lines = Get-Content 'input.txt' $lines | Sort-Object | Set-Content 'input.txt' Write-Output "File sorted in-place"
This overwrites the original file; use with caution to avoid data loss.
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
All lines are loaded into memory, so space used is proportional to the number of lines, O(n).
Which Approach is Fastest?
Using Sort-Object is efficient and built-in; sorting in-place saves disk space but risks data loss.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-Content + Sort-Object + Set-Content | O(n log n) | O(n) | Safe sorting with separate output file |
| Get-Content + Sort-Object + Out-File | O(n log n) | O(n) | Similar to Set-Content but with encoding control |
| In-place sorting with overwrite | O(n log n) | O(n) | When you want to replace original file quickly |
Always back up your original file before sorting in-place to prevent accidental data loss.
Forgetting to save the sorted output back to a file, so the original file remains unchanged.