Linux: sed to replace across multiple files in directory

sed is an excellent utility for doing substitutions, but if you need to work across multiple files, then you need to pair it with a command that can provide a list of candidate files.  This is where find comes in handy.

For example, to replace all instances of ‘zebra’ with ‘horse’ recursively in the current directory.

find . -type f -exec sed -i 's/zebra/horse/g' {} \;

find‘ is attractive because it can limit the output to just files (directories would cause sed to throw errors), and you can also specify whether it should be recursive (the default), or you want to limit the depth.

Here is the reverse replacement, but limited to just files in the immediate directory (not subfolders) ending with ‘.txt’.

find . -maxdepth 1 -type f -name '*.txt' -exec sed -i 's/horse/zebra/g' {} \;

REFERENCES

man sed

man find

stackoverflow, replace string in all files of directory