How can I sort lines in a text file without changing the original?
Quick answer
On systems with GNU Coreutils, run sort filename.txt to display sorted lines in the terminal; by default, GNU sort sends results to standard output rather than replacing the input. To keep a sorted copy, redirect output to a different filename. Check your system’s sort behavior and locale first, because ordering can vary and options can change it. [S1]
The question, the details, the next step.
A practical checklist
Confirm which
sortutility your system provides; the behavior described here is GNU-specific.Run
sort input.txtwithout redirection to preview the result.Check that all lines are present and the displayed ordering meets your expectations.
If needed, verify how your system’s locale and chosen options affect ordering.
Save only to a distinct output filename, then inspect that copy.
A few more useful answers
Does `sort input.txt` overwrite the input file?
For GNU sort, the default output goes to standard output, not back into the named input file. [S1] Don’t assume every platform’s sort behaves identically.
Why does the order differ from what I expected?
GNU sort uses the active locale’s character-collating sequence, and options can change which keys or ordering are used. [S1] Check the preview and your system’s documentation rather than assuming a universal order.
Can I make a sorted copy without changing the original?
On a shell using GNU sort, redirect the output to a different filename, such as sort input.txt > sorted-copy.txt. Make sure the output path is not the input path.
Sources
References used for this guide.
- [S1] GNU Coreutils 9.11: sort text files gnu.org · Checked
