2014-02-18 86 views
0

我经常发现自己将一系列shell命令串起来,最终目标是替换文件的内容。但是,使用>时,会打开原始文件进行写入,因此您将丢失所有内容。覆盖文件的内容:替代`>`?

缺少一个更好的术语,是否有一个“懒惰评估”版本的>,将等到所有先前的命令已经在打开文件写入前执行过?

目前我使用:

somecommand file.txt | ... | ... > tmp.txt && rm file.txt && mv tmp.txt file.txt 

这是相当难看。

回答

1

sponge将帮助这里:

(从手册页引用)

名称 海绵 - 沉浸标准输入和写入文件

提要 sed的 '...'文件| grep'...'|海绵文件

说明 海绵读取标准输入并将其写出到指定文件。 与shell重定向不同,海绵会在打开 输出文件之前吸收其所有输入。这允许构建从中读取的管道和从 写入相同的文件。

It also creates the output file atomically by renaming a temp file into 
    place, and preserves the permissions of the output file if it already 
    exists. If the output file is a special file or symlink, the data will 
    be written to it. 

    If no output file is specified, sponge outputs to stdout. 

参见:Can I read and write to the same file in Linux without overwriting it? on unix.SE