0
0
Linux CLIscripting~5 mins

sed substitution in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you need to quickly change words or letters inside a text file or output without opening an editor. The sed substitution command lets you do this by finding text and replacing it with new text right from the command line.
When you want to fix a typo in a configuration file without opening an editor.
When you need to replace all occurrences of a word in a log file to anonymize data.
When you want to change a specific string in multiple files using a script.
When you want to test how a text looks with some words changed before saving.
When you want to quickly replace text in the output of another command.
Commands
This command replaces the word 'world' with 'there' in the text 'Hello world'. It shows how sed substitution works on a simple string.
Terminal
echo "Hello world" | sed 's/world/there/'
Expected OutputExpected
Hello there
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 replaces all occurrences of 'apple' with 'orange' in the file fruits.txt and saves the changes directly to the file using the -i flag.
Terminal
sed -i 's/apple/orange/g' fruits.txt
Expected OutputExpected
No output (command runs silently)
-i - Edit the file in place, saving changes directly
g - Replace all occurrences on each line, not just the first
This command finds the word 'apple' and adds the word 'pie' after it using grouping \( \) and backreference \1.
Terminal
sed 's/\(apple\)/\1 pie/' fruits.txt
Expected OutputExpected
apple pie pie apple juice apple tart pie
Key Concept

If you remember nothing else from this pattern, remember: sed substitution uses s/old/new/ to find and replace text, and flags like g and -i control how and where replacements happen.

Common Mistakes
Forgetting to escape special characters like slashes in the search or replacement text.
sed will misinterpret the command and give errors or wrong output.
Use backslashes \ to escape special characters or choose a different delimiter like s|old|new|.
Not using the -i flag when you want to save changes to the file.
sed will only print the changed text to the screen but will not modify the file.
Add the -i flag to edit the file in place.
Not using the g flag when you want to replace all occurrences on a line.
Only the first match on each line will be replaced, leaving others unchanged.
Add the g flag at the end of the substitution command to replace all matches.
Summary
Use sed substitution with s/old/new/ to replace text in streams or files.
Add the g flag to replace all matches on each line, not just the first.
Use the -i flag to save changes directly to the file instead of just printing.