0
0
Bash Scriptingscripting~5 mins

sed for substitution in scripts in Bash Scripting

Choose your learning style9 modes available
Introduction
You use sed substitution to quickly find and replace text in files or outputs without opening them. It helps automate text changes in scripts.
Fix a typo in many lines of a configuration file automatically.
Change a word in a log file before sharing it.
Update a version number in multiple files during deployment.
Replace placeholders in a template file with real values.
Clean up output text by removing or changing certain words.
Syntax
Bash Scripting
sed 's/old-text/new-text/' filename

# or for inline replacement in a script
sed 's/old-text/new-text/g' <<< "$variable"
The 's' means substitute. It looks for 'old-text' and replaces it with 'new-text'.
Adding 'g' after the last slash means replace all occurrences in a line, not just the first.
Examples
Replaces the first 'cat' with 'dog' on each line of animals.txt.
Bash Scripting
sed 's/cat/dog/' animals.txt
Replaces all 'cat' words with 'dog' on each line.
Bash Scripting
sed 's/cat/dog/g' animals.txt
Replaces 'Hello' only if it is at the start of a line.
Bash Scripting
sed 's/^Hello/Hi/' greetings.txt
Replaces the first 'dog' with 'cat' in the given string.
Bash Scripting
sed 's/dog/cat/' <<< "I have a dog and a dog."
Sample Program
This script creates a file with some lines about cats. It then shows how sed replaces the first 'cat' per line and then all 'cat' words per line with 'dog'.
Bash Scripting
#!/bin/bash

# Create a sample file
cat <<EOF > pets.txt
I have a cat.
My cat is cute.
Cats are playful.
EOF

# Show original file
echo "Original file contents:"
cat pets.txt

echo
# Replace first 'cat' with 'dog' on each line
sed 's/cat/dog/' pets.txt > pets_replaced.txt

echo "After replacing first 'cat' with 'dog' on each line:"
cat pets_replaced.txt

echo
# Replace all 'cat' (case sensitive) with 'dog' on each line
sed 's/cat/dog/g' pets.txt > pets_replaced_all.txt

echo "After replacing all 'cat' with 'dog' on each line:"
cat pets_replaced_all.txt
OutputSuccess
Important Notes
Time complexity is generally linear to the size of the input text because sed reads line by line.
Space complexity is low since sed streams the input and does not load entire files into memory.
A common mistake is forgetting the 'g' flag, which only replaces the first match per line.
Use sed substitution when you want quick, scriptable text changes without opening editors.
Summary
sed substitution lets you find and replace text easily in scripts.
Use 's/old/new/' to replace the first match per line, add 'g' to replace all matches.
It is great for automating text edits in files or variables.