How to use sed to find and replace text in files in Linux / Unix shell
Find and replace text within a file using sed command
The procedure to change the text in files under Linux/Unix using sed:
- Use Stream EDitor (sed) as follows:
- sed -i 's/old-text/new-text/g' input.txt
- It tells sed to find all occurrences of ‘old-text‘ and replace with ‘new-text‘ in a file named input.txt
- The s is the substitute command of sed for find and replace. The -i tells to update the file. The / is the default delimiter, but it can be any character other than a backslash (\)[1] or newline (\n)[1] can be used instead of a slash (/) to delimit the regex and the replacement. For example, use \ character as delimiter instead of the default / to find all occurrences of ‘FOO‘ and replace with ‘BAR‘ on GNU/Linux sed (the command will not work on BSD/macOS sed):
- sed -i 's\FOO\BAR\g' input.txt
## OR use the ‘@‘ as delimiter that works on GNU and BSD/macOS sed version ## - sed -i 's@FOO@BAR@g' input.txt
- Verify that file has been updated: more input.txt