-1

the file word-count.txt contains the text:

10
2
19
22
6

why does typing the command sort -n word-count.txt > word-count.txt wipe the memory of the file? I understand that there are other ways of saving the sorted list of numbers into a file but why is it when I save it into the file where the numbers are contained suddenly there is no data there?

IMSoP
  • 89,526
  • 13
  • 117
  • 169
A Zhitom
  • 9
  • 4
  • 1
    This is a common question, and searching this site and others you'll find lots of explanations; the first one I came across on this site is this: [Find and replace in file and overwrite file doesn't work, it empties the file](https://stackoverflow.com/questions/5171901/find-and-replace-in-file-and-overwrite-file-doesnt-work-it-empties-the-file) – IMSoP Oct 03 '20 at 12:49

1 Answers1

1

Becuase when you use > to redirect the output of a command to a file, it recreates the file, meaning there is no longer anything in it to sort in the first place.

If you want to do this you'll have to create a temporary file first then rename it over the original:

sort word-count.txt > wc_temp.txt && mv wc_temp.txt word-count.txt
michjnich
  • 2,796
  • 3
  • 15
  • 31