覆盖文件的内容:替代`>`? [英] overwrite contents of a file: alternative to `>`?

查看:51
本文介绍了覆盖文件的内容:替代`>`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I often find myself stringing together a series of shell commands, ultimately with the goal to replace the contents of a file. However, when using > it opens the original file for writing, so you lose all the contents.

由于缺乏更好的术语,是否存在> 的惰性评估"版本,该版本将等到所有先前的命令都执行完之后,再打开要写入的文件?

For lack of a better term, is there a "lazy evaluation" version of > that will wait until all the previous commands have been executed before before opening the file for writing?

当前我正在使用:

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

哪个很丑.

推荐答案

海绵在这里有帮助:

(从联机帮助页引用)

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

NAME sponge - soak up standard input and write to a file

简介sed'...'文件|grep'...'|海绵锉

SYNOPSIS sed '...' file | grep '...' | sponge file

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

DESCRIPTION sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file. This allows constructing pipelines that read from and write to the same file.

  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.

另请参见:我可以在Linux中读写同一文件而不覆盖它吗?在unix.SE

这篇关于覆盖文件的内容:替代`>`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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