0
0
Linux CLIscripting~10 mins

sed substitution in Linux CLI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - sed substitution
Read input line
Match pattern?
NoPrint line unchanged
Yes
Replace matched text
Print modified line
Repeat for next line
End
sed reads each line, checks if it matches the pattern, replaces matched text if yes, then prints the line.
Execution Sample
Linux CLI
echo 'apple banana apple' | sed 's/apple/orange/'
Replace first 'apple' with 'orange' in the input line.
Execution Table
StepInput LinePattern MatchActionOutput Line
1apple banana appleYes (apple found)Replace first 'apple' with 'orange'orange banana apple
2No more linesN/AEnd of inputN/A
💡 No more input lines to process, sed ends.
Variable Tracker
VariableStartAfter Step 1Final
input_lineapple banana appleapple banana appleNo more lines
pattern_matchedfalsetrueN/A
output_lineorange banana apple
Key Moments - 2 Insights
Why does sed only replace the first occurrence of 'apple'?
By default, sed's 's/pattern/replacement/' replaces only the first match per line, as shown in execution_table step 1.
What happens if the pattern is not found in the line?
sed prints the line unchanged.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output line after step 1?
Aapple banana apple
Bapple banana orange
Corange banana apple
Dorange orange apple
💡 Hint
Check the 'Output Line' column in execution_table row for step 1.
At which step does sed stop processing input lines?
AStep 1
BStep 2
CAfter Step 1
DNever stops
💡 Hint
Look at the 'Step' and 'Action' columns in execution_table for when input ends.
If we add 'g' flag to sed like 's/apple/orange/g', how would the output line change at step 1?
Aorange banana orange
Borange banana apple
Capple banana apple
Dorange orange orange
💡 Hint
The 'g' flag replaces all matches per line, not just the first, affecting output_line in variable_tracker.
Concept Snapshot
sed substitution syntax: s/pattern/replacement/ 
By default replaces first match per line.
Add 'g' flag to replace all matches.
Reads input line by line, applies substitution, prints result.
Useful for quick text changes in scripts or command line.
Full Transcript
sed substitution reads each input line, checks if the pattern matches. If yes, it replaces the first occurrence of the pattern with the replacement text and prints the modified line. If no match, it prints the line unchanged. This process repeats for all input lines until none remain. By default, only the first match per line is replaced unless the 'g' flag is added to replace all matches. This makes sed a powerful tool for quick text editing in command line scripts.