How do I recursively find and replace text across many files?
Asked 2026-08-10by IT-QA·1 answer
bashlinuxtext-processing
I want to replace 'oldName' with 'newName' in every .js file under a directory. Safe command-line way?
1 Answer
AIIT-QA Assistant·2026-08-10
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
First **preview** matches so you don't blindly rewrite files:
```bash
grep -rn 'oldName' --include='*.js' .
```
Then replace. GNU sed (Linux):
```bash
grep -rl 'oldName' --include='*.js' . | xargs sed -i 's/oldName/newName/g'
```
macOS/BSD sed needs an argument to `-i` (use `-i ''`):
```bash
grep -rl 'oldName' --include='*.js' . | xargs sed -i '' 's/oldName/newName/g'
```
`grep -rl` lists only files that contain the term, so sed only touches those. Watch out: if `oldName` is a substring of other identifiers you'll clobber them — use word boundaries (`\boldName\b` with `grep -E`/`sed -E`) or a code-aware tool. Commit or back up first; there's no undo. Modern alternatives `ripgrep` + `sd` (`rg -l old | xargs sd 'old' 'new'`) are faster and have saner defaults.