如何将 StdOut 添加到文件顶部(而不是底部)?

发布于 2025-01-07 16:40:13 字数 233 浏览 4 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

九命猫 2025-01-14 16:40:13
echo a | cat - file1 > file2

与 shellter

和 sed 一样在一行中。

sed -i -e '1 i<whatever>' file1

这将插入到 file1 中。
sed我提到的例子

echo a | cat - file1 > file2

same as shellter's

and sed in one line.

sed -i -e '1 i<whatever>' file1

this will insert to file1 inplace.
the sed example i referred to

落日海湾 2025-01-14 16:40:13

tac 是非常“昂贵”的解决方案,特别是当您需要使用它两次时。虽然您仍然需要使用 tmp 文件,但这将花费更少的时间:

编辑来自 KeithThompson 的注释,现在使用“.$$”文件名和条件 /bin/mv

  { 
     echo "a" 
     cat file1
  } > file1.$  && /bin/mv file1.$ file1

我希望这有帮助

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.

  { 
     echo "a" 
     cat file1
  } > file1.$  && /bin/mv file1.$ file1

I hope this helps

好多鱼好多余 2025-01-14 16:40:13

使用命名管道就地替换sed,您可以在文件顶部添加命令的输出,而无需明确需要临时文件:

mkfifo output
your_command >> output &
sed -i -e '1x' -e '1routput' -e '1d' -e '2{H;x}' file
rm output

它的作用是在命名管道 (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:

mkfifo output
your_command >> output &
sed -i -e '1x' -e '1routput' -e '1d' -e '2{H;x}' file
rm output

What this does is buffering the output of your_command in a named pipe (fifo), and inserts in place this output using the r command of sed. For that, you need to start your_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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文