Hello! Welcome back to our series on Bash scripting.
In the last lesson, you mastered how to handle command-line arguments, making your scripts flexible and interactive. Now that your scripts can accept input, the next logical step is to learn how to process and transform text-based data, which is a daily task in DevOps.
Today, you'll learn how to use one of the most powerful text-processing utilities in the Linux toolkit: sed. The name stands for stream editor, and it's essential for automating tasks like editing configuration files, parsing log data, and transforming command output in your scripts.
Today's Learning Outcome: By the end of this lesson, you will be able to perform text substitution and filtering on data streams using sed.
1. What is a Stream Editor?
Unlike a text editor like vim or nano that you use interactively, sed is non-interactive. It reads text from an input stream (either a file or piped data), applies a set of commands to each line, and then sends the modified result to an output stream (by default, your terminal screen).
This line-by-line processing model makes sed incredibly efficient and perfect for use within scripts where you need to make changes programmatically without manual intervention.
To get started, let's explore the fundamental concepts of how sed works.
The Basics of Using the Sed Stream Editor to Manipulate Text in Linux
This tutorial from DigitalOcean provides an excellent introduction to sed. It explains what a stream editor is, how it processes input, and its basic command structure.
Please read the 'Introduction' and 'Basic Usage' sections. Set up the example BSD file as instructed, as we'll use it throughout this lesson. Pay close attention to how sed can operate on both a file directly and on standard input from a pipe (|).
As you saw in the reading, running sed with an empty command (sed '' BSD) simply prints the file's content, much like the cat command. The real power of sed is unlocked when we start giving it commands to execute.
2. Filtering: Selecting Which Lines to Process
Before you can modify text, you often need to select which lines you want to affect. sed allows you to do this using addresses. An address can be a single line number, a range of lines, or a pattern to search for.
Two fundamental commands for filtering are:
d: Delete the lines that match the address.p: Print the lines that match the address. When usingp, you should almost always use the-ncommand-line option, which suppressessed's default behavior of printing every line.
Let's continue with the DigitalOcean tutorial to see how this works.
The Basics of Using the Sed Stream Editor to Manipulate Text in Linux
These sections demonstrate how to use addresses to filter a stream. You'll learn how to select lines by number and then how to either print or delete them.
Read the sections 'Printing Lines', 'Using Address Ranges', and 'Deleting Text'. As you read, try the examples on the BSD file you created. Notice the difference between sed '1,5p' BSD (with duplicate lines) and sed -n '1,5p' BSD (with only the selected lines).
A key takeaway from the reading is that sed does not modify the original file by default. It sends the transformed output to standard output. To save the changes, you can redirect the output to a new file:
sed '/pattern/d' input.log > cleaned.log
You can also edit "in-place" with the -i flag, but this is destructive. It overwrites the original file.
Warning: Use the -i flag with extreme caution. It's best practice to first run your sed command without -i to verify the output. When you are ready to edit in-place, consider creating a backup simultaneously by providing an extension, like sed -i.bak 's/old/new/' file.conf. This will perform the edit on file.conf and save the original content in file.conf.bak.
Test your understanding!
Imagine you have a log file named app.log.
- How would you display only lines 50 through 100?
- How would you create a new file named
app_errors.logthat contains only the lines fromapp.logwhich include the word "ERROR"? - How would you remove all lines containing the word "DEBUG" from
app.logand save the changes back to the same file (creating a backup first)?
Show answer
sed -n '50,100p' app.logsed -n '/ERROR/p' app.log > app_errors.log(or, more simply,grep 'ERROR' app.log > app_errors.log)sed -i.bak '/DEBUG/d' app.log
3. Substitution: Finding and Replacing Text
The most common use of sed is for substitution using the s command. Its basic syntax is 's/find/replace/flags'. This is the workhorse of sed and is invaluable for tasks like updating configuration settings in a script.
Let's look at a simple example. Here, we first use grep to see the original lines, and then use sed to replace "Software" with "SOFTWARE_JOB".

The real power comes from the flags and regular expressions you can use.
The Basics of Using the Sed Stream Editor to Manipulate Text in Linux
This final section of the tutorial covers the powerful substitution command, which you'll use constantly in your DevOps work. It explains the core syntax, important flags, and how to use regular expressions for advanced replacements.
Read the section 'Substituting Text' and its subsection 'Replacing and Referencing Matched Text'. Pay close attention to: The g flag for global replacement. Using a number (2, 3, etc.) to replace a specific occurrence on a line. Changing the delimiter from / to another character (e.g., _ or |) to handle text containing slashes, like file paths. Using & to re-insert the entire matched pattern in the replacement string. Using $ ... $ and \1 to capture and reuse parts of the matched pattern.
As the reading explains, you can replace a specific occurrence of a pattern. For instance, the command sed 's/Bash/Shell/2' file.txt would only replace the second time "Bash" appears on each line.

Using Variables in sed
In your scripts, you'll often need to use variables in your sed command. Since single quotes (') prevent variable expansion, you must use double quotes (").
#!/bin/bash
OLD_VALUE="dev"
NEW_VALUE="prod"
CONFIG_FILE="settings.conf"
echo "server_env=${OLD_VALUE}" > ${CONFIG_FILE}
echo "Original file:"
cat ${CONFIG_FILE}
# Use double quotes to allow variables to be expanded
sed -i "s/server_env=${OLD_VALUE}/server_env=${NEW_VALUE}/" ${CONFIG_FILE}
echo "Modified file:"
cat ${CONFIG_FILE}
Test your understanding!
- You have a file
hosts.txtwith the lineIP address: 192.168.1.10. How would you wrap the IP address in square brackets to getIP address: [192.168.1.10]? - You have a CSV file
users.csvwith lines likedoe,john. How would you swap the first and last names to getjohn,doe? - How would you change the path
/usr/local/binto/opt/binin a file namedconfig.sh?
Show answer
-
Use the
&to reference the matched pattern:sed 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/[&]/' hosts.txt
This uses a regular expression to find an IP-like pattern and the&re-inserts that matched IP inside square brackets. -
Use capturing groups:
sed 's/$.*$,$.*$/\2,\1/' users.csv$and$create two capture groups (everything before the comma, and everything after).\2,\1then reverses their order in the replacement. -
Use an alternative delimiter to avoid escaping the slashes:
sed -i 's|/usr/local/bin|/opt/bin|g' config.sh
Using|as the delimiter is much cleaner thans/\/usr\/local\/bin/\/opt\/bin/g.
Conclusion
You've now added sed to your command-line arsenal. You've learned how to filter data streams and perform powerful find-and-replace operations. This skill is fundamental for automating the modification of text-based files, a cornerstone of configuration management and log analysis in DevOps.
Key Takeaways:
sedis a stream editor that processes text line-by-line from standard input or a file.- By default,
sedprints its output to the screen and does not alter the original file. Use output redirection (>) to save to a new file or the-iflag to edit in-place (with caution!). - You can filter lines using addresses (line numbers, ranges, or patterns) combined with commands like
d(delete) andp(print with-n). - The
s/find/replace/flagscommand is the most common. Key flags includeg(global) andi(case-insensitive). - You can use
&to reference the entire matched pattern and\1,\2, etc., to reference captured groups for complex transformations.
In our next lesson, we will explore another giant of text processing: awk. While sed excels at whole-line operations, awk is designed to work with structured, field-based data (like columns in a log file), making it the perfect companion to sed.