输入和输出重定向到同一个文件 [英] input and output redirection to the same file

查看:295
本文介绍了输入和输出重定向到同一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能输入输出重定向到一般相同的文件?我的意思是特别有 -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.

这篇关于输入和输出重定向到同一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆