使用 grep 进行就地处理
我有一个调用 grep 来处理文本文件的脚本。目前我正在做这样的事情。
$ grep 'SomeRegEx' myfile.txt > myfile.txt.temp
$ mv myfile.txt.temp myfile.txt
我想知道是否有任何方法可以进行就地处理,例如将结果存储到同一原始文件中,而无需创建临时文件,然后在处理完成时用临时文件替换原始文件。
当然,我欢迎评论为什么应该这样做或不应该这样做,但我主要感兴趣的是是否可以这样做。在此示例中,我使用的是 grep
,但我对一般的 Unix 工具很感兴趣。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
sponge
(在moreutils
包中在 Debian/Ubuntu 中)读取输入直到 EOF 并将其写入文件,因此您可以 grep 文件并将其写回自身。像这样:
sponge
(inmoreutils
package in Debian/Ubuntu) reads input till EOF and writes it into file, so you can grep file and write it back to itself.Like this:
Perl 有
-i
开关,sed
和Ruby
也有,但请注意,它所做的只是在后端创建“临时”文件你认为你看不到的,仅此而已。
之外的其他方式
除了
grep
awkbash
Perl has the
-i
switch, so doessed
andRuby
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
bash
不,一般情况下在 Unix 中是做不到这样的。您只能创建/截断(使用 >)或附加到文件(使用 >>)。一旦被截断,旧的内容就会丢失。
No, in general it can't be done in Unix like this. You can only create/truncate (with >) or append to a file (with >>). Once truncated, the old contents would be lost.
一般来说,这是无法做到的。但 Perl 有
-i
开关:写入
-i.bak
会导致原始文件保存在myfile.txt.bak
中。(当然,在内部,Perl 基本上只是做你已经在做的事情——不涉及任何特殊的魔法。)
In general, this can't be done. But Perl has the
-i
switch:Writing
-i.bak
will cause the original to be saved inmyfile.txt.bak
.(Of course internally, Perl just does basically what you're already doing -- there's no special magic involved.)
大多数
sed
安装都可以进行就地编辑,请检查手册页,您可能需要-i
标志。Most installations of
sed
can do in-place editing, check the man page, you probably want the-i
flag.要使用 vim-way 就地编辑文件,请尝试:
或者使用
sed
或gawk
。To edit file in-place using vim-way, try:
Alternatively use
sed
orgawk
.存储在变量中,然后将其分配给原始文件:
Store in a variable and then assign it to the original file:
请参阅我的幻灯片“Perl 命令行选项现场指南”,网址为 http:// /petdance.com/perl/command-line-options.pdf 了解有关使用 Perl 可以做什么的更多想法。
Take a look at my slides "Field Guide To the Perl Command-Line Options" at http://petdance.com/perl/command-line-options.pdf for more ideas on what you can do in place with Perl.
这将在 myfile.txt 中找到一些文本并将其保存回 myfile.txt,这将完成你想要的。不确定正则表达式,但它确实适用于文本。
This will find sometext in myfile.txt and save it back to myfile.txt, this will accomplish what you want. Not sure about regex, but it does work for text.