使用 grep 就地处理 [英] In-place processing with grep
问题描述
我有一个调用 grep 来处理文本文件的脚本.目前我正在做这样的事情.
I've got a script that calls grep to process a text file. Currently I am doing something like this.
$ grep 'SomeRegEx' myfile.txt > myfile.txt.temp
$ mv myfile.txt.temp myfile.txt
我想知道是否有任何方法可以进行就地处理,例如将结果存储到同一个原始文件中,而无需创建临时文件,然后在处理完成后用临时文件替换原始文件.
I'm wondering if there is any way to do in-place processing, as in store the results to the same original file without having to create a temporary file and then replace the original with the temp file when processing is done.
当然,我欢迎评论为什么应该或不应该这样做,但我主要感兴趣的是它是否可以.在这个例子中,我使用了 grep
,但我对 Unix 工具很感兴趣.谢谢!
Of course I welcome comments as to why this should or should not be done, but I'm mainly interested in whether it can be done. In this example I'm using grep
, but I'm interested about Unix tools in general. Thanks!
推荐答案
Perl 有 -i
开关,sed
和 Ruby
也有
Perl has the -i
switch, so does sed
and Ruby
sed -i.bak -n '/SomeRegex/p' file
ruby -i.bak -ne 'print if /SomeRegex/' file
但请注意,它所做的只是在后端创建您认为看不到的临时"文件,仅此而已.
But note that all it ever does is creating "temp" files at the back end which you think you don't see, that's all.
其他方式,除了grep
awk
awk '/someRegex/' file > t && mv t file
重击
while read -r line;do case "$line" in *someregex*) echo "$line";;esac;done <file > t && mv t file
这篇关于使用 grep 就地处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!