Artificial intelligent assistant

append string where it belongs in sorted file Suppose I have a sorted file, named sorted.txt, like this: beautiful easy fast functional handy Now, doing `echo fine-grained >> sorted.txt` will put "fine-grained" at the end of the file, after "handy". Is there a way to insert it in order, between "fast" and "functional", without needing to re-sort the file?

Although theoretically possible, there isn't a magic way to do this.

If you knew exactly what value you wanted to place it after you could use `sed` in-place search and replace to stick the new value in the file, but given the complexities of sorting, it basically comes down to you are going to have to sort it somewhere long the line.


echo fine-grained >> sorted.txt
sort sorted.txt > sorted.txt.new && mv sorted.txt{.new,}


Or with `sponge`:


{ echo fine-grained ; cat sorted.txt } | sort | sponge sorted.txt


**Edit:** Gilles made a good suggestion for using the `-m` argument for sort to potentially speed this up. From the manual:

>
> -m, --merge
> merge already sorted files; do not sort
>

This would keep sort from processing all the way through the input, it only has to scan through the input files and figure out their relation to each other.


echo fine-grained | sort -m sorted.txt - | sponge sorted.txt

xcX3v84RxoQ-4GxG32940ukFUIEgYdPy e933410d998d6663c357fee50f8f1bda