如何在命令中使用文件并将输出重定向到同一个文件而不截断它? [英] How can I use a file in a command and redirect output to the same file without truncating it?
问题描述
基本上我想从文件中获取输入文本,从该文件中删除一行,然后将输出发送回同一个文件.如果这能让事情更清楚的话,应该遵循这些原则.
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.
#!/bin/sh
tmpfile=$(mktemp)
grep -v 'seg[0-9]{1,}.[0-9]{1}' file_name > ${tmpfile}
cat ${tmpfile} > file_name
rm -f ${tmpfile}
像那样,考虑使用 mktemp
来创建 tmpfile 但请注意它不是 POSIX.
like that, consider using mktemp
to create the tmpfile but note that it's not POSIX.
这篇关于如何在命令中使用文件并将输出重定向到同一个文件而不截断它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!