Coder Perfect

How to sort a file while it’s open


When we execute the sort file command, the contents of the file are sorted. But what if I don’t want any other result than a sorted file?

Asked by Ali Sajid

Solution #1

You can reroute the sorted out files using file redirection.

sort input-file > output_file

Alternatively, you may use the sort -o, —output=FILE option to specify the same input and output file:

sort -o file file

Without mentioning the name of the file (with bash brace expansion)

sort -o file{,}

Note: Trying to redirect the output to the same input file (e.g. sort file > file) is a typical mistake. This does not work because the shell makes the redirections (not the sort(1) software), and the input file (which also serves as the output) gets wiped immediately before the sort(1) programme can read it.

Answered by Sylvain Bugat

Solution #2

The sort command prints the result of the sorting operation to standard output by default. You can obtain a “in-place” sort by doing the following:

sort -o file file

This replaces the input file with the output that has been sorted. Because the -o switch, which specifies an output, is established by POSIX, it should work with any version of sort:

If you have a version of sort that doesn’t contain the -o switch (Luis informs me that they exist), you can do a “in-place” update in the usual way:

sort file > tmp && mv tmp file

Answered by Tom Fenech

Solution #3

sort file | sponge file

This can be found in the Fedora package:

moreutils : Additional unix utilities
Repo        : fedora
Matched from:
Filename    : /usr/bin/sponge

Answered by SilverlightFox

Solution #4

Here’s a method that (ab)uses vim:

vim -c :sort -c :wq -E -s "${filename}"

After the file opens, the -c:sort -c:wq part runs vim commands. The -E and -s options are required for vim to run in a “headless” mode that does not draw to the terminal.

Except for the fact that it only takes the filename input once, this has absolutely no advantages over sort -o “$filename” “$filename.”

This helped me implement a formatter directive for.gitignore files in a nanorc entry. This is what I used to do it:

syntax "gitignore" "\.gitignore$"

formatter vim -c :sort -c :wq -E -s

Answered by Anthony Sottile

Solution #5

Try the following to sort the file in the right place:

echo "$(sort your_file)" > your_file

You can’t immediately route the output back to the input file, as described in earlier responses. However, you can first evaluate the sort command before redirecting it back to the original file. You can use this method to implement in-place sorting.

You can also use this method to build row-wise adding with other commands like paste.

Answered by Bo Tian

Post is based on