如何在Perl中替换现有文件中的字符串而不触及未改变的文件 [英] How to replace a string in an existing file in Perl while not touching unchanged files
问题描述
perl -pi -e's / pattern / replacement / g'$(find src -type f)
不错,除了一件事:所有文件都被覆盖,即使没有任何匹配。这不是很好,因为我经常保持在Emacs或Eclipse中的许多开放,然后问我无聊的问题。是否有一个简单的方法,如何防止接触不变的文件(像使用grep查找是太多的工作,特别是对于复杂的模式)。
>打开文件后,第一件 -i
是 unlink
它,这意味着你可以对你不想修改的文件使用 -i
。
找到src -type f -exec grep -Pl'pattern'{} + |
xargs perl -i -pe's / pattern / replacement / g'
当然, code> grep 已经可以执行递归搜索,所以除非你需要使用 find
来进一步过滤结果,你可以使用
grep -Plr'pattern'src |
xargs perl -i -pe's / pattern / replacement / g'
注意: cmd | xargs perl ...
可以处理比 perl更多的文件... $(cmd)
。
Using
perl -pi -e 's/pattern/replacement/g' $(find src -type f)
is nice, except for one thing: All files get overwritten, even those without any match. This is not good as I often keep many of them open in Emacs or Eclipse which then ask me boring questions. Is there a simple way how to prevent touching unchanged files (Something like using grep in find is too much work, especially for complex patterns).
The very first thing -i
after opening a file is to unlink
it, so that means you can't use -i
on the files you don't want to modify.
find src -type f -exec grep -Pl 'pattern' {} + |
xargs perl -i -pe's/pattern/replacement/g'
Of course, grep
can already perform recursive searches, so unless you need to use find
to filter the results further than you indicated, you can use
grep -Plr 'pattern' src |
xargs perl -i -pe's/pattern/replacement/g'
Note: cmd | xargs perl ...
can handle more files than perl ... $( cmd )
.
这篇关于如何在Perl中替换现有文件中的字符串而不触及未改变的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!