如何在命令中使用文件并将输出重定向到同一文件而不截断它? [英] How can I use a file in a command and redirect output to the same file without truncating it?

查看:130
本文介绍了如何在命令中使用文件并将输出重定向到同一文件而不截断它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想从文件中获取输入文本,从该文件中删除一行,然后将输出发送回同一文件。如果这样可以使它更清楚。

Basically I want to take as input text from a file, remove a line from that file, and send the output back to the same file. Something along these lines if that makes it any clearer.

grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name > file_name

然而,当我这样做时,我最终得到一个空白文件。
有什么想法吗?

however, when I do this I end up with a blank file. Any thoughts?

推荐答案

你不能这样做,因为bash首先处理重定向,然后执行命令。所以当grep查看file_name时,它已经是空的。你可以使用一个临时文件。

You cannot do that because bash processes the redirections first, then executes the command. So by the time grep looks at file_name, it is already empty. You can use a temporary file though.

grep -v 'seg[0-9]\{1,\}\.[0-9]\{1\}' file_name > tmpfile
cat tmpfile > file_name

这样,考虑使用 mktemp 来创建 tmpfile 但请注意它不是POSIX。

like that, consider using mktemp to create the tmpfile but note that it's not POSIX.

这篇关于如何在命令中使用文件并将输出重定向到同一文件而不截断它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆