Find and Replace Text Within File in Linux

Last updated on Dec 30, 2019 in Linux

You can find and replace text within a file or multiple files with a single one-liner in Linux. The command we are using is sed.

In this example, our task is to replace text foo to bar in the file index.html:

$ sed -i 's/foo/bar/g' index.html
  • -i stands for in-place edit meaning that file is updated
  • s is a command for sed to substitute texts
  • g replaces all occurences, not just the first one

You can open the file and verify that all foos are now bars.

You can search and replace text also in multiple files as well. For example, let’s replace foo to bar in all HTML files within the current working directory:

$ sed -i 's/foo/bar/g' *.html

sed is a powerful utility that can modify file content from command line. It is also quite complex to use when you try to do more complicated things. Check man sed for further information.