replace text in many files
Change a word or a phrase in every file under a folder that contains it.
Steps
-
grep -rl 'old' .first, see which files contain it
-
grep -rl 'old' . | xargs sed -i 's/old/new/g'change it in all of them
-
find . -name '*.txt' -exec sed -i 's/old/new/g' {} +only in the .txt files
-
git diffin a git repository, check what changed
Notes
- Run it in a git repository or on a copy: a wrong pattern changes many files at once.
- macOS:
sed -i ''in place ofsed -i.
Commands used
grepsedfindxargs
Each has a page in lore: lore grep opens it.
Related recipes
- compare two foldersFind which files differ between two folders, or are only in one of them.
- count lines, words and filesCount the lines of a file or of a command's output, the words, and the files in a folder.
- delete lines containing a textRemove every line of a file that contains a word, or keep only those lines.
- find files containing a textSearch every file under a folder for a word or a phrase, and show where it is.