Complete Linux sed Command Guide

Overview

Introducing the powerful stream editor sed command, which allows you to quickly and accurately replace and edit text file content in a Linux environment. Learn easily through practical examples, ranging from basic string substitution to specific line deletion, as well as the in-place editing (-i) option that modifies files directly while creating backups.

1. Practice Environment Setup and Basic String Substitution with sed (s Command)

To safely practice sed commands, run mkdir -p ~/sed_practice && cd ~/sed_practice to create a dedicated directory and navigate to it.

mkdir -p ~/sed_practice && cd ~/sed_practice

To create sample text for the string substitution exercise, run echo -e 'apple is delicious\nbanana is yellow\napple is red' > fruits.txt to write the content into a file.

echo -e ‘apple is delicious\nbanana is yellow\napple is red’ > fruits.txt

The sed command is a stream editor that parses and transforms text streams.
Using the s substitution operator, it replaces the first occurrence of the string apple with orange on each line and prints the result to the screen.
The original fruits.txt file remains unchanged, and only the output is displayed via standard output.
⚙️ [Key Options]

-i : Directly modifies and saves the original file instead of displaying the output on the screen.
-e : Chains and executes multiple editing script commands at once.
-n : Suppresses automatic printing of pattern space and only prints explicitly specified lines.
-E or -r : Enables and uses Extended Regular Expression (ERE) syntax.

sed ’s/apple/orange/’ fruits.txt

Appending the g flag to the end of the substitution expression replaces all matching targets globally within a line.
Use this when multiple instances of the same search term exist on a line and you want to replace them all without omission.

sed ’s/apple/orange/g’ fruits.txt

2. Selective Line Output and Line Deletion (d and -n Options)

To prepare log data required for line selection and deletion exercises, run echo -e 'Line 1: Server OK\nLine 2: Server Warning\nLine 3: Server Error\nLine 4: Server OK' > server.log to create a sample file.

echo -e ‘Line 1: Server OK\nLine 2: Server Warning\nLine 3: Server Error\nLine 4: Server OK’ > server.log

Combining the -n option with the p command prints only lines 2 through 3 to the screen within the specified range.
This is useful when suppressing default automatic output and selectively inspecting specific lines of interest.

sed -n ‘2,3p’ server.log

Using the d command with pattern matching excludes lines containing the Warning string and outputs only the remaining lines to the screen.
Use this to filter out unnecessary logs or lines matching specific conditions.

sed ‘/Warning/d’ server.log

Specify a line number and execute the d command to output the result after deleting the 2nd line.
Utilize this when you want to remove a line at a specific line number and inspect the file content.

sed ‘2d’ server.log

3. Direct File Modification and Automatic Backup (-i Option)

To practice modifying configuration files, create a config.env file containing sample environment variable data.

echo -e ‘PORT=8080\nDEBUG=true\nTIMEOUT=30’ > config.env

Using the -i.bak option creates a backup file config.env.bak of the original file, while simultaneously replacing DEBUG=true with DEBUG=false and saving it directly to the original file.
Take advantage of this when directly editing original files while safely preserving the pre-modification state.

sed -i.bak ’s/DEBUG=true/DEBUG=false/’ config.env

Check the contents of the modified config.env file using the cat command.
You can confirm that the DEBUG value has been successfully changed to false and applied to the file.

cat config.env

Print and verify the content of the automatically generated backup file, config.env.bak.
You can see that the original pre-edit state DEBUG=true is preserved intact, ensuring a safe backup.

cat config.env.bak

4. Advanced Text Substitution Using Regular Expressions and Custom Delimiters

To create sample file path data for the path substitution exercise, write content to paths.txt using the echo command.

echo -e ‘Old path: /usr/local/bin\nNew path: /usr/local/bin’ > paths.txt

Using the pipe symbol (|) as the substitution delimiter instead of the default slash (/), safely substitute /usr/local/bin with /usr/bin within the path and print the output.
When working with file paths or URLs containing slashes, this allows you to write clean expressions without escape characters (\).

sed ’s|/usr/local/bin|/usr/bin|g’ paths.txt

To practice removing whitespace using regular expressions, create a sample spaces.txt file containing leading and trailing whitespace.

echo -e ’   leading spaces\nno spaces\n   trailing removed   ’ > spaces.txt

Matching the ^ anchor representing the start of a line with the [ \t]* regular expression targeting space and tab characters removes all leading whitespace from each line and displays the output.
This is particularly useful when batch-cleaning indentation whitespace in documents or log data.

sed ’s/^[ \t]*//’ spaces.txt

So far, we have covered the essential usage of the Linux sed command, from basic text substitution to bulk file modification.
As it is a powerful tool that dramatically reduces repetitive file editing tasks, make sure to take advantage of it whenever needed.