Shell one-liner to add a line to a sorted file

pipe, sed, shell, sorting

Solution

echo "New Line" | sort -o file - file

The `-o file` means write result to file (and it is explicitly safe to have any of the input files as the output file). The `-` on its own means 'read standard input' which contains the new line of information. The `file` at the end means 'also read `file`'. This would work with any Unix sort from (at least) 7th Edition UNIX™ circa 1978 onwards, and possibly even before that. There are no temporary files or dependencies on other utilities.

Given that a single line is 'sorted' and the file is also in sorted order, you can probably speed the process up by just merging the two sorted inputs:

echo "New Line" | sort -o file -m - file

That also would have worked with even really old sort commands.

Problem

I want to add a line to a text file so that the result is sorted, where the text file was originally sorted. For example: ``` cp file tmp; echo "new line" >> tmp; sort tmp > file; rm -f tmp ``` I'd REALLY like to do it w/o the temp file and w/o the semicolons (using pipes instead?); using `sed` would be acceptable. Is this possible, and if so, how?

Original source