覆盖文件的内容:替换为`>`?

时间:2014-02-18 23:43:01

标签: bash

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

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

目前我正在使用:

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

哪个很难看。

1 个答案:

答案 0 :(得分:1)

sponge会在这里提供帮助:

(从联机帮助页面引用)

  

NAME          海绵 - 吸收标准输入并写入文件

     

概要          sed'...'文件| grep'...'|海绵文件

     

说明          sponge读取标准输入并将其写入指定文件。          与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