How do I execute any command editing its file (

2019-01-12 21:16发布

I have a file temp.txt, that I want to sort with the sort command in bash.

I want the sorted results to replace the original file.

This doesn't work for example (I get an empty file):

sortx temp.txt > temp.txt

Can this be done in one line without resorting to copying to temporary files?


EDIT: The -o option is very cool for sort. I used sort in my question as an example. I run into the same problem with other commands:

uniq temp.txt > temp.txt.

Is there a better general solution?

14条回答
做自己的国王
2楼-- · 2019-01-12 22:06

Many have mentioned the -o option. Here is the man page part.

From the man page:

   -o output-file
          Write output to output-file instead of to the  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  output-
          file.
查看更多
Melony?
3楼-- · 2019-01-12 22:07

Read up on the non-interactive editor, ex.

查看更多
倾城 Initia
4楼-- · 2019-01-12 22:11

Use the argument --output= or -o

Just tried on FreeBSD:

sort temp.txt -otemp.txt
查看更多
时光不老,我们不散
5楼-- · 2019-01-12 22:15

Another solution:

uniq file 1<> file
查看更多
我只想做你的唯一
6楼-- · 2019-01-12 22:16

If you insist on using the sort program, you have to use a intermediate file -- I don't think sort has an option for sorting in memory. Any other trick with stdin/stdout will fail unless you can guarantee that the buffer size for sort's stdin is big enough to fit the entire file.

Edit: shame on me. sort temp.txt -o temp.txt works excellent.

查看更多
干净又极端
7楼-- · 2019-01-12 22:17
sort temp.txt -o temp.txt
查看更多
登录 后发表回答