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:

  1. Use Stream EDitor (sed) as follows:
  2. sed -i 's/old-text/new-text/g' input.txt
  3. It tells sed to find all occurrences of ‘old-text‘ and replace with ‘new-text‘ in a file named input.txt
  4. 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):
  5. sed -i 's\FOO\BAR\g' input.txt
    ## OR use the ‘@‘ as delimiter that works on GNU and BSD/macOS sed version ##
  6. sed -i 's@FOO@BAR@g' input.txt
  7. Verify that file has been updated: more input.txt

 

Similar Posts