bash:如何在不使用辅助文件的情况下将文件编辑到自身中 -
注意:我特别在寻找编码黑客,而不是为了替代解决方案。我知道awk
,sed
等可以很好地完成此内联编辑。
$ 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将内容存储在shell变量中,而不是文件中。
请注意,这可能仅适用于文本文件,而不适用于二进制文件。如果您需要处理它们,则可以在管道中使用编码/解码命令。
如果不将数据存储在某个地方,则不能这样做。当您将输出重定向到文件时,Shell立即将文件截断。如果使用管道,管道中的命令将与外壳同时运行,并且它将不可预测,它将首先运行 - 外壳截断文件或试图从中读取的命令。
You can store the content in a shell variable rather than a file.
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.
感谢@Cyrus对原始问题的评论,
它确实需要安装额外的软件包并使用诸如Sponge 检查是否已安装的
之类的内容进行预先检查。
With thanks to the comment made by @Cyrus to the original question
It does require installing an extra package and pre-checking for the binary using something like
where sponge
to check if it is installed.如果您碰巧使用
macos
,如果文件不太gargantuan,则可以始终按照以下步骤操作:执行编辑
将其置于剪贴板上(或Mac Lingo中的“粘贴”)
将其粘贴到原始文件名
|
if you happen to use
macos
, if the file isn't too gargantuan, you can always follow these steps :perform the edits
pipe it to the clipboard (or "pasteboard" in mac lingo)
paste it back to original file name
|