Sort a file without using temporary files

I want to sort a file in a unix shell. Can I redirect my result to my input file?

eg. if my input file is foo, can I use

sort foo > foo 

or should I use:

  sort -o foo foo 

What is the difference between the two above?

Thanks,

+4
source share
1 answer

Using

 sort -o foo foo 

On the man page:

-o OUTPUT-FILE' Write output to OUTPUT-FILE instead of standard output. If OUTPUT-FILE is one of the input files, -o OUTPUT-FILE' Write output to OUTPUT-FILE instead of standard output. If OUTPUT-FILE is one of the input files, sort 'copies it to a temporary file before sorting and writing the output to the Output file.

sort foo > foo means writing output to standard output, which is redirected to the output file. Before redirecting > will crop / overwrite the output file if it exists. Since both input and output files are the same, you will lose information about the input files.

+8
source

All Articles