How to Find and Replace Text Within a File Using Command Line in Ubuntu
Topic: Ubuntu / LinuxPrev|Next
Answer: Use 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.
-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
Or, if you prefer absolute path you can run the following command.
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.
Here are some more FAQ related to this topic:
- How to change current working directory in Ubuntu terminal
- How to rename a directory via command line in Ubuntu
- How to copy the contents of a folder to another folder from terminal in Ubuntu