How to search and replace text within a text file using the Command Line on Linux

Written by Ian Carnaghan · 47 sec read >
  • Knowledge Base
  • Linux
  • How to search and replace text within a text file using the Command Line on Linux

This can be accomplished by using the sed command.

sed =  stream editor for filtering and transforming text


For this example we will have a file called test.txt that contains the following text This is a test file with some test information, containing some test data.

We want to replace all instances of test in the file with cool and save the output to a new file called cool.txt

To accomplish this open a new command line window and type and execute the following command:

sed -e 's/test/cool/g' test.txt > cool.txt

-e =  add the script to the commands to be executed
s = s/regexp/replacement/
Attempt  to match regexp against the pattern space.  If success‐
ful,  replace  that  portion  matched  with  replacement.    The
replacement may contain the special character & to refer to that
portion of the pattern space  which  matched,  and  the  special
escapes  \1  through  \9  to refer to the corresponding matching
sub-expressions in the regexp.

g = Copy/append hold space to pattern space.


If you view cool.txt by using the cat command

cat cool.txt

you’ll see the following output

This is a cool file with some cool information, containing some cool data.

To learn more about the set command type in man sed in the command line

man sed

Last Updated On April 07, 2018
Written by Ian Carnaghan
I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment. Profile

Leave a Reply

Notify of