unix - 对 stdin 和 stdout 使用相同的文件进行重定向

标签 unix pipe

我正在编写一个充当过滤器的应用程序:它从文件 (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/

相关文章:

macos - 有没有办法打开一系列新的终端窗口,并在单个脚本中运行命令?

linux - 如何使用 sed 将文本替换为 ":"

c - 不使用 pipe() 获取两个文件描述符

c - 多个子进程将使用 popen 执行的 unix 命令的结果写入父进程

c++ - 多个 fork() 带管道的 child

c - 管道、子进程和子进程的范围

Erlang:如何将 stdin 输入从文件传输到 erlang 程序并匹配 eof?

bash - 使用 sed 将变量打印到文件末尾

java - Runtime.getRuntime.exec ("who am i") 没有给出预期的结果

linux - 搜索字符串的标准命令