How to Find and Replace Text Within a File Using Command Line in Ubuntu
belongs to collection: Ubuntu / Linux Frequently Asked Questions
All Answers
total answers (1)
belongs to collection: Ubuntu / Linux Frequently Asked Questions
total answers (1)
Use the
sed
UtilityThe
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.
The option
-i
(in-place) tellssed
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.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
need an explanation for this answer? contact us directly to get an explanation for this answer/
is an absolute path.