0
0
Linux CLIscripting~5 mins

sed (stream editor) basics in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to quickly change text inside files or streams without opening an editor. sed helps you do this by reading text line by line and applying simple rules to change it automatically.
When you want to replace a word in a file without opening a text editor.
When you need to delete specific lines from a file based on a pattern.
When you want to print only certain lines from a file that match a condition.
When you want to quickly transform text output from another command.
When you want to save time by automating simple text edits in scripts.
Commands
This command replaces the word 'world' with 'sed' in the text 'Hello world'. It shows how sed can change text in a stream.
Terminal
echo "Hello world" | sed 's/world/sed/'
Expected OutputExpected
Hello sed
This command replaces the first occurrence of 'apple' with 'orange' on each line of the file fruits.txt and prints the result to the screen.
Terminal
sed 's/apple/orange/' fruits.txt
Expected OutputExpected
orange pie orange juice orange tart
This command does the same replacement as before but changes the file fruits.txt directly (in-place).
Terminal
sed -i 's/apple/orange/' fruits.txt
Expected OutputExpected
No output (command runs silently)
-i - Edit the file in-place instead of printing to screen
This command deletes all lines starting with '#' from config.txt and prints the result. Useful to remove comments.
Terminal
sed '/^#/d' config.txt
Expected OutputExpected
port=8080 host=localhost mode=production
This command prints only lines 2 to 4 from data.txt. The -n flag tells sed not to print anything else.
Terminal
sed -n '2,4p' data.txt
Expected OutputExpected
line 2 content line 3 content line 4 content
-n - Suppress automatic printing of all lines
Key Concept

If you remember nothing else from sed, remember: it reads text line by line and applies simple rules to change or select text automatically.

Common Mistakes
Using sed without the -i flag when you want to change the file permanently.
Without -i, sed only prints the changed text but does not save it to the file.
Add the -i flag to edit the file directly if you want permanent changes.
Forgetting to escape special characters like '/' in the sed pattern.
sed uses '/' as a delimiter, so unescaped '/' in patterns cause errors.
Escape '/' with a backslash '\/' or use a different delimiter like 's#old#new#'.
Not using -n when you only want to print specific lines.
sed prints all lines by default, so without -n you get extra unwanted output.
Use -n to suppress automatic printing and then use p command to print desired lines.
Summary
sed can replace text in streams or files using simple substitution commands.
Use the -i flag to save changes directly to files.
You can delete or print specific lines using patterns and line ranges.