简体   繁体   English

除了某些文件之外,递归查找和替换

[英]Find & replace recursively except for certain files

With regards to this post , how would I exclude one or more files from applying the string replacement? 关于这篇文章 ,我如何排除一个或多个文件应用字符串替换? By using the aforementioned post as an example, I would like to be able to replace "apples" with "oranges" in all descendant files of a given directory except , say, ./fpd/font/symbol.php . 通过使用上述职位为例,我希望能够在不同的 ,也就是说,一个给定目录的所有后代文件“橘子”,以取代“苹果” ./fpd/font/symbol.php

My idea was using the -regex switch in the find command but unfortunately it does not have a -v option like the grep command hence I can't negate the regex to not match the files where the replacement must occur. 我的想法是在find命令中使用-regex开关,但不幸的是它没有像grep命令那样的-v选项,因此我无法否定正则表达式与必须进行替换的文件匹配。

没有测试过,但它应该工作:

find . -path ./fpd/font/symbol.php -prune -o -exec sed -i 's/apple/orange/g' {} \;

You can negate with ! 你可以否定! (or -not ) combined with -name : (或-not )与-name结合使用:

$ find .
.
./a
./a/b.txt
./b
./b/a.txt
$ find . -name \*a\* -print
./a
./b/a.txt
$ find . ! -name \*a\* -print
.
./a/b.txt
./b
$ find . -not -name \*a\* -print
.
./a/b.txt
./b

I use this in my Git repository: 我在我的Git存储库中使用它:

grep -ilr orange . | grep -v ".git" | grep -e "\\.php$" | xargs sed -i s/orange/apple/g {}

It will: 它会:

  1. Run find and replace only in files that actually have the word to be replaced; 仅在实际具有要替换的单词的文件中运行查找和替换;
  2. Not process the .git folder; 不处理.git文件夹;
  3. Process only .php files. 仅处理.php文件。

Needless to say you can include as many grep layers you want to filter the list that is being passed to xargs . 毋庸置疑,您可以包含多个grep图层,以便过滤传递给xargs的列表。

Known issues: 已知的问题:

At least in my Windows environment it fails to open files that have spaces in the path or name. 至少在我的Windows环境中,它无法打开路径或名称中包含空格的文件。 Never figured that one out. 从未想过那一个。 If anyone has an idea of how to fix this I would like to know. 如果有人知道如何解决这个问题,我想知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM