VenomFangs VenomFangs - 6 months ago 17
Bash Question

Recursive Sed Against Files that Match a Directory Pattern

Is there an easy way to use

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


foobar


I could run the following:

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


Resulting in the text of the file being:


barbar


Is there a way to specify a directory pattern like:

somedir/**/example.txt


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

Answer

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' {} +

Documentation

From man bash (version 4+):

globstar
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.