输入和输出重定向到同一个文件

输入和输出重定向到同一个文件

问题描述:

我怎么能输入输出重定向到一般相同的文件?我的意思是特别有 -o 排序命令,并有可能对不同的命令其他类似的选项。但是,我怎么能一般输入输出重定向到同一个文件,而不重挫文件?

How can I redirect input and output to a same file in general? I mean specifically there is -o for sort command and there might be other such options for various command. But how can I generally redirect input and output to same file without clobbering the file?

例如:排序A.TXT> A.TXT 破坏A.TXT文件的内容,但我想答案存储在同一个文件。我知道我可以使用 MV RM 使用临时文件,但它是可以直接做后?

For example: sort a.txt > a.txt destroys the a.txt file contents but I want to store answer in the same file. I know I can use mv and rm after using temporary file, but is it possible to do it directly?

作为的 BashPitfalls条目#13 ,则可以使用海绵 moreutils 来吸收打开文件之前将数据写入到它。

As mentioned on BashPitfalls entry #13, you can use sponge from moreutils to "soak up" the data before opening the file to write to it.

使用示例:
排序A.TXT |海绵A.TXT

虽然BashPitfalls页提到,有可能是数据丢失,海绵手册页说。

While the BashPitfalls page mentions that there could be data loss, the man page for sponge says

它还通过重命名一个临时文件到位创建输出文件原子[...]

It also creates the output file atomically by renaming a temp file into place [...]

这会使它没有更多的危险比写入一个临时文件,并做了 MV

This would make it no more dangerous than writing to a temp file and doing a mv.

感谢查尔斯达菲以指出在评论中BashPitfalls项。

Credit to Charles Duffy for pointing out the BashPitfalls entry in the comments.