VenomFangs VenomFangs - 2 years ago 73
Bash Question

Recursive Sed Against Files that Match a Directory Pattern

Is there an easy way to use

to replace text in files that match a directory pattern? For example, if I had a file called
which contained the following text:


I could run the following:

sed -i -e 's/foo/bar/g' somedir/example.txt

Resulting in the text of the file being:


Is there a way to specify a directory pattern like:


Which would recursively update any
file under the
folder? If there is an easier way to accomplish this, I'm game too.

Answer Source

If you have bash version 4, run

shopt -s globstar
sed -i -e 's/foo/bar/g' somedir/**/example.txt

If you have an earlier version bash or just a POSIX shell, then run:

find somedir -type f -name 'example.txt' -exec sed -i -e 's/foo/bar/g' {} +

For OSX:

find somedir -type f -name 'example.txt' -exec sed -i '' -e 's/foo/bar/g' {} +


From man bash (version 4+):

If set, the pattern ** used in a pathname expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download