如何将 StdOut 添加到文件顶部(而不是底部)?
我在 Linux 中使用 bash 来完成将内容添加到文件顶部的操作。 到目前为止,我知道我可以通过使用临时文件来完成此操作。所以 我这样做是这样的:
tac lines.bar > lines.foo
echo "a" >> lines.foo
tac lines.foo > lines.bar
但是有没有更好的方法可以做到这一点而不必编写第二个文件?
I am using bash with linux to accomplish adding content to the top of a file.
Thus far i know that i am able to get this done by using a temporary file. so
i am doing it this way:
tac lines.bar > lines.foo
echo "a" >> lines.foo
tac lines.foo > lines.bar
But is there a better way of doing this without having to write a second file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与 shellter
和 sed 一样在一行中。
这将插入到 file1 中。
sed我提到的例子
same as shellter's
and sed in one line.
this will insert to file1 inplace.
the sed example i referred to
tac 是非常“昂贵”的解决方案,特别是当您需要使用它两次时。虽然您仍然需要使用 tmp 文件,但这将花费更少的时间:
编辑来自 KeithThompson 的注释,现在使用“.$$”文件名和条件
/bin/mv
。我希望这有帮助
tac is very 'expensive' solution, especially as you need to use it 2x. While you still need to use a tmp file, this will take less time:
edit per notes from KeithThompson, now using '.$$' filename and condtional
/bin/mv
.I hope this helps
使用命名管道和就地替换与
sed
,您可以在文件顶部添加命令的输出,而无需明确需要临时文件:它的作用是在命名管道 (fifo) 中缓冲
your_command
的输出,并使用r
插入该输出就地sed
命令。为此,您需要在后台启动your_command
以避免阻塞 fifo 中的输出。注意,r命令在循环结束时输出文件,因此我们需要将文件的第一行缓冲在保留空间中,与第二行一起输出。
我编写时没有明确需要临时文件,因为 sed 可能会自己使用一个临时文件。
Using a named pipe and in place replacement with
sed
, you could add the output of a command at the top of a file without explicitly needing a temporary file:What this does is buffering the output of
your_command
in a named pipe (fifo), and inserts in place this output using ther
command ofsed
. For that, you need to startyour_command
in the background to avoid blocking on output in the fifo.Note that the
r
command output the file at the end of the cycle, so we need to buffer the 1st line of file in the hold space, outputting it with the 2nd line.I write without explicitly needing a temporary file as
sed
might use one for itself.