Console9

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

  1. Use find with sed -i to replace a string in all .conf files under a directory:

    find /etc/nginx/ -name "*.conf" -exec sed -i 's/old_domain/new_domain/g' {} +
  2. Use grep and xargs for 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'
  3. 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.