WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Find and Replace Text Within a File Using Command Line in Ubuntu

Topic: Ubuntu / LinuxPrev|Next

Answer: Use the sed Utility

The sed utility is a stream editor that can be used to read or edit one or more text files.

You can use the following syntax to find and replace text within a file using terminal in Ubuntu.

sed -i 's/original/new/gi' filename.txt

The option -i (in-place) tells sed to write the changes to the original file.

The substitution expression have the following meanings:

  • s : The beginning of the substitution expression.
  • original : Represents the word or substring to replace (can also be a regular expression).
  • new : Represents the replacement word or substring.
  • g : Represent global i.e. replace all occurrences.
  • i : Represent ignoreCase i.e. case-insensitive search and replacement.

For example, let's consider your current working directory is /var/www and you've a text file named "sample.txt" inside it, which just contains the text "Twinkle Twinkle Little Star".

Now if you want to replace every occurrence of the word "Twinkle" with the word "Shiny" in the "sample.txt" file, you can simply use the following sed command.

sed -i 's/Twinkle/Shiny/gi' sample.txt

Or, if you prefer absolute path you can run the following command.

sed -i 's/Twinkle/Shiny/gi' /var/www/sample.txt

Both commands will have the same effect, because current working directory doesn't matter when you use absolute path. Any path that starts with a forward slash / is an absolute path.


Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties