我正在编写一个充当过滤器的应用程序:它从文件 (stdin) 读取输入、处理并将输出写入另一个文件 (stdout)。输入文件在应用程序开始写入输出文件之前被完全读取。
由于我使用的是标准输入和标准输出,我可以像这样运行:
$ ./myprog <file1.txt >file2.txt
它工作正常,但是如果我尝试使用相同的文件作为输入和输出(即:从文件读取,然后写入同一个文件),如下所示:
$ ./myprog <file.txt >file.txt
它清洁
file.txt
在程序有机会阅读它之前。有什么办法可以在 Unix 的命令行中做这样的事情吗?
最佳答案
在 moreutils 中有一个海绵实用程序包裹:
./myprog < file.txt | sponge file.txt
引用手册:
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.
关于unix - 对 stdin 和 stdout 使用相同的文件进行重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897451/