replace text in a file
Change every place a word or a phrase appears in a file, keeping a copy if you like.
Steps
-
sed 's/old/new/g' file.txtshow the file with every old turned into new, without changing it
-
sed -i 's/old/new/g' file.txtchange the file itself
-
sed -i.bak 's/old/new/g' file.txtthe same, keeping the old one as file.txt.bak
-
sed -i '0,/old/s//new/' file.txtonly the first one in the file (GNU sed)
-
sed -i 's|/old/path|/new/path|g' file.txttext with slashes: another separator
Notes
- macOS:
sed -i '' 's/old/new/g' file.txt. sed 's/…/…/' file > fileempties the file: write to a new one, or use -i.
Commands used
sedperl
Each has a page in lore: lore sed 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.