Video Coming Soon...

Created by Zed A. Shaw Updated 2026-08-31 20:32:57
 

07: Introducing sed

To this point you've been using grep (and ugrep on Windows) to only search for patterns in text. This is useful but it'd be more useful if you could replace patterns with other text. In this exercise you'll learn to use the command line tool sed to use regex patterns to "search and replace."

What Is Sed

The tool sed stands for "stream editor" and it's purpose is to input a "stream" of text (usually a file), scan each line for a regex pattern, and then replace any matches with alternative text.

The simplest way to run sed is like this:

sed s/pattern/replace/g

If you run this command in your Terminal you can actually enter text, hit ENTER and sed will do its job:

$ sed s/pattern/replace/g
This is a pattern
This is a replace
That I pattern
That I replace
Nobody needs to pattern
Nobody needs to replace

To exit this hold ctrl and hit d so ctrl-d.

The first line is one I typed, then next line is the one sed prints and you can see it replaced pattern with replace. This continues with each line, and be sure you understand I only type every odd line, sed outputs the even ones.

The format of this sed command is like this:

s
substitute this is the sed command to run.
/
bounding character This starts the regex, and you can actually use any character so another popular one is ,. You need this because sometimes the text you're searching has / in it so as long as each bounding character matches you can use what you want.
pattern
regex You can use any regex here to match in lines.
/
bounding Again, this is your bounding character, and if you chose , you'd use that instead.
replace
replacement This is what you want the regex to be replaced with.
/
bounding One more time to end the pattern, but you need one more little thing.
g
modifiers You can add special modifiers to your s// command, and this one says "global" which means replace all occurrences on each line. If you don't have this sed will only replace the first occurrence of pattern.

Be sure you understand how this works and try a few more of your own. The more time you spend playing with basic input and regex the more prepared you'll be for later.

Previous Lesson Next Lesson

Register for Learn Regex the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.