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:17

Tobu's comment on sponge warrants being an answer in its own right.

To quote from the moreutils homepage:

Probably the most general purpose tool in moreutils so far is sponge(1), which lets you do things like this:

% sed "s/root/toor/" /etc/passwd | grep -v joey | sponge /etc/passwd

However, sponge suffers from the same problem Steve Jessop comments on here. If any of the commands in the pipeline before sponge fail, then the original file will be written over.

$ mistyped_command my-important-file | sponge my-important-file
mistyped-command: command not found

Uh-oh, my-important-file is gone.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-12 22:20

I like the sort file -o file answer but don't want to type the same file name twice.

Using BASH history expansion:

$ sort file -o !#^

grabs the current line's first arg when you press enter.

A unique sort in-place:

$ sort -u -o file !#$

grabs the last arg in the current line.

查看更多
登录 后发表回答