How to replace text in multiple files with sed
Find and replace a string across multiple files using sed with find or xargs on Linux.
How to replace text in multiple files with sed
Find and replace a string across multiple files using sed with find or xargs on Linux.
Prerequisites
- GNU sed installed (default on Linux).
Step-by-Step: Replace Text in Multiple Files with sed
Use
findwithsed -ito replace a string in all.conffiles under a directory:find /etc/nginx/ -name "*.conf" -exec sed -i 's/old_domain/new_domain/g' {} +Use
grepandxargsfor faster processing — grep finds files containing the string, then sed modifies only those files:grep -rl "old_domain" /etc/nginx/ | xargs sed -i 's/old_domain/new_domain/g'Preview changes before applying by omitting
-i:grep -rl "old_domain" /etc/nginx/ | xargs sed 's/old_domain/new_domain/g'
Common Issues When Replacing in Multiple Files with sed
On macOS (BSD sed), use
-i '' instead of
-i. The GNU and BSD versions of sed handle in-place editing differently.