Tuesday, June 7, 2022

[SOLVED] How to sort a file in-place?

Issue

When we use the sort file command, the file shows its contents in a sorted way. What if I don't want to get any output on stdout, but in the input file instead?


Solution

You can use the -o, --output=FILE option of sort to indicate the same input and output file:

sort -o file file

Without repeating the filename (with bash brace expansion)

sort -o file{,}

⚠️ Important note: a common mistake is to try to redirect the output to the same input file (e.g. sort file > file). This does not work as the shell is making the redirections (not the sort(1) program) and the input file (as being the output also) will be erased just before giving the sort(1) program the opportunity of reading it.



Answered By - Sylvain Bugat
Answer Checked By - Willingham (WPSolving Volunteer)