find & sed (search and replace)

I’m using the following command on my mac:

$find . -name “*.java” -exec sed -i ’s/foo/bar/g’ {} ;

and it seems to have no effect.

I have two files in the directory that end in .java, which both have the foo text in them. Am I missing something?

Results from request of comments

[aafghani-03:~/test amirafghani]$ find . -name "*.java" -exec sed -i 's/foo/bar/g' {} ;
sed: 1: "./": invalid command code .
sed: 1: "./": invalid command code .


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

First of all, make sure you’re using regular ascii quotes like " and ' (ascii codes 0x22 and 0x27, respectively) in shell scripts, because the example in your post contains non-standard quote characters. If you look closely, they look a bit different. Most probably this is a copy-paste error from a rich text document format like Word, OOWriter, or even a browser window.

Since you’re on a Mac, you most probably have the FreeBSD implementation of sed, in which case you have to write the command this way:

find . -name "*.java" -exec sed -i '' "s/foo/bar/g" {} +

(here using + instead of ; to avoid running one sed invocation per file).

Note that those quotes around "s/foo/bar/g" are necessary if foo or bar have spaces.

In the FreeBSD implementation of sed the -i flag needs an argument: the extension of a backup file. For example with -i .bak the command would backup file1.txt as file1.txt.bak first before performing the replacement in the original file. Using an empty argument '' means to not use a backup file, which seems to be what you want.

The same thing in the GNU (or NetBSD, OpenBSD, busybox) implementation would be:

find . -name "*.java" -exec sed -i "s/foo/bar/g" {} +

Thank you @bahamat and @Mikel and @pieter-breed for improving my answer with your comments.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments