对标准输入和标准输出使用相同的文件并进行重定向
我正在编写一个充当过滤器的应用程序:它从文件(stdin)读取输入,处理并将输出写入另一个文件(stdout)。在应用程序开始写入输出文件之前,输入文件已完全读取。
由于我使用的是标准输入和标准输出,我可以这样运行:
$ ./myprog <file1.txt >file2.txt
它工作正常,但如果我尝试使用相同的文件作为输入和输出(即:从文件读取,然后写入同一文件),像这样:
$ ./myprog <file.txt >file.txt
它会在程序有机会读取 file.txt
之前清理它。
有什么办法可以在 Unix 的命令行中做这样的事情吗?
I'm writing a application that acts like a filter: it reads input from a file (stdin), processes, and write output to another file (stdout). The input file is completely read before the application starts to write the output file.
Since I'm using stdin and stdout, I can run is like this:
$ ./myprog <file1.txt >file2.txt
It works fine, but if I try to use the same file as input and output (that is: read from a file, and write to the same file), like this:
$ ./myprog <file.txt >file.txt
it cleans file.txt
before the program has the chance to read it.
Is there any way I can do something like this in a command line in Unix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
moreutils 包中有一个海绵实用程序:
引用手册:
There's a sponge utility in moreutils package:
To quote the manual:
shell 会破坏输出文件,因为它在执行程序之前准备输出文件句柄。在 shell 在单个 shell 命令行中破坏文件之前,无法让程序读取输入。
您需要使用两个命令,在读取文件之前移动或复制文件:
或者输出到副本,然后替换原始文件:
如果您不能这样做,那么您需要将文件名传递给您的程序,该程序将打开文件处于读/写模式,并在内部处理所有 I/O。
The shell is what clobbers your output file, as it's preparing the output filehandles before executing your program. There's no way to make your program read the input before the shell clobbers the file in a single shell command line.
You need to use two commands, either moving or copying the file before reading it:
Or else outputting to a copy and then replacing the original:
If you can't do that, then you need to pass the filename to your program, which opens the file in read/write mode, and handles all the I/O internally.
对于纯粹学术性质的解决方案:
可能有问题的副作用是:
./myprog
失败,则会破坏您的输入。 (自然...)./myprog
从子 shell 运行(使用{ ... ; }
而不是( ... )
来避免。)file.txt
成为具有新 inode 和文件权限的新文件。file.txt
目录具有+w
权限。For a solution of a purely academic nature:
Possibly problematic side-effects are:
./myprog
fails, you destroy your input. (Naturally...)./myprog
runs from a subshell (Use{ ... ; }
instead of( ... )
to avoid.)file.txt
becomes a new file with a new inode and file permissions.+w
permission on the directory housingfile.txt
.