bash:如何在不使用辅助文件的情况下将文件编辑到自身中 -

发布于 2025-02-10 12:34:44 字数 327 浏览 2 评论 0原文

注意:我特别在寻找编码黑客,而不是为了替代解决方案。我知道awksed等可以很好地完成此内联编辑。

$ echo '1' > test
$ cat test > test
$ cat test
$ 

有没有办法,以某种方式使第二个命令输出原始内容(在这种情况下为1)?同样,我正在寻找一个可以使用的黑客,而无需明显地使用辅助文件(在后台使用辅助文件是可以的)。这个论坛上的另一个问题仅着眼于替代解决方案,这不是我想要的。

Note: I am particularly looking for a coding hack, not for an alternative solution. I am aware that awk, sed etc. can do this inline edit just fine.

$ echo '1' > test
$ cat test > test
$ cat test
$ 

Is there a way, to somehow make the second command output the original contents (1 in this case)? Again, I am looking for a hack which will work without visibly having to use a secondary file (using a secondary file in the background is fine). Another question on this forum solely focused on alternative solutions which is not what I am looking for.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

转身泪倾城 2025-02-17 12:34:44

您可以将内容存储在shell变量中,而不是文件中。

var=$(<test)
printf "%s\n" "$var" > test

请注意,这可能仅适用于文本文件,而不适用于二进制文件。如果您需要处理它们,则可以在管道中使用编码/解码命令。

如果不将数据存储在某个地方,则不能这样做。当您将输出重定向到文件时,Shell立即将文件截断。如果使用管道,管道中的命令将与外壳同时运行,并且它将不可预测,它将首先运行 - 外壳截断文件或试图从中读取的命令。

You can store the content in a shell variable rather than a file.

var=$(<test)
printf "%s\n" "$var" > test

Note that this might only work for text files, not binary files. If you need to deal with them you can use encoding/decoding commands in the pipeline.

You can't do it without storing the data somewhere. When you redirect output to a file, the shell truncates the file immediately. If you use a pipeline, the commands in the pipeline run concurrently with the shell, and it's unpredictable which will run first -- the shell truncating the file or the command that tries to read from it.

樱娆 2025-02-17 12:34:44

感谢@Cyrus对原始问题的评论,

$ sudo apt install moreutils
$ echo '1' > test
$ cat test | sponge test
$ cat test
1

它确实需要安装额外的软件包并使用诸如Sponge 检查是否已安装的之类的内容进行预先检查。

With thanks to the comment made by @Cyrus to the original question

$ sudo apt install moreutils
$ echo '1' > test
$ cat test | sponge test
$ cat test
1

It does require installing an extra package and pre-checking for the binary using something like where sponge to check if it is installed.

纸伞微斜 2025-02-17 12:34:44

如果您碰巧使用macos,如果文件不太gargantuan,则可以始终按照以下步骤操作:

  1. 执行编辑
  2. 将其置于剪贴板上(或Mac Lingo中的“粘贴”)
  3. 将其粘贴到原始文件名

|

{... edits to file1 ...} | pbcopy; pbpaste > file1 

if you happen to use macos, if the file isn't too gargantuan, you can always follow these steps :

  1. perform the edits
  2. pipe it to the clipboard (or "pasteboard" in mac lingo)
  3. paste it back to original file name

|

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