2

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.

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.

Community
  • 1
  • 1
Andrea Aloi
  • 971
  • 1
  • 17
  • 37

3 Answers3

1

Haven't tested this but it should work:

find . -path ./fpd/font/symbol.php -prune -o -exec sed -i 's/apple/orange/g' {} \;
armandino
  • 17,625
  • 17
  • 69
  • 81
1

You can negate with ! (or -not) combined with -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
1

I use this in my Git repository:

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;
  3. Process only .php files.

Needless to say you can include as many grep layers you want to filter the list that is being passed to xargs.

Known issues:

At least in my Windows environment it fails to open files that have spaces in the path or name. Never figured that one out. If anyone has an idea of how to fix this I would like to know.

Havenard
  • 27,022
  • 5
  • 36
  • 62
  • This works great! I tuned it slightly like so: `default="myApp"; grep -Rl $default . | grep -v ".git" | grep -v "angular.js" | grep -v $0 | xargs sed -i "s/$default/somethingElse/g";` Basically what id does is replace the default name of an angularjs-seed application ("myApp") to something else (can be user-defined) in the entire project except for inside the .git folder, the file angular.js (where it appears as an example inside a comment block) and in the script itself. Great answer! :) – Andrea Aloi Oct 29 '13 at 18:59
  • By the way, adding {} at the end of the command as per your example causes the following warning: `sed: can't read {}: No such file or directory` so I omitted it and it works like a charm! – Andrea Aloi Oct 29 '13 at 19:05