使用grep进行就地处理 [英] In-place processing with grep

查看:204
本文介绍了使用grep进行就地处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用grep来处理文本文件的脚本。目前我正在做这样的事情。

  $ grep'SomeRegEx'myfile.txt> myfile.txt.temp 
$ mv myfile.txt.temp myfile.txt

I' m想知道是否有任何方法可以进行就地处理,如将结果存储到相同的原始文件而不必创建临时文件,然后在处理完成后用temp文件替换原始文件。



当然,我欢迎评论为什么应该这样做,但我主要关心它是否可以完成。在这个例子中,我使用 grep ,但是我对Unix工具一般很感兴趣。谢谢!

解决方案

Perl有 -i 开关, code> sed 和 Ruby

  sed -i.bak -n'/ SomeRegex / p'文件

ruby​​ -i.bak -ne'打印if / SomeRegex /'文件

但是请注意,它所做的只是在后端创建临时文件,而您认为这些文件您没有看到,就这些了。除了 grep



awk

  awk'/ someRegex /'文件> t&& mv t file 



bash

  while read -r line; do * someregex *中的情况$ lineecho$ line;; esac; done< file> t&& mv t file 


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.

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 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.

Other ways, besides grep

awk

awk '/someRegex/' file > t && mv t file

bash

while read -r line;do case "$line" in *someregex*) echo "$line";;esac;done <file > t && mv t file

这篇关于使用grep进行就地处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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