0
0
Bash Scriptingscripting~5 mins

sed for substitution in scripts in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the sed command do in a script?

sed is a tool that edits text by searching and replacing patterns. It reads input line by line and can change text automatically.

Click to reveal answer
beginner
How do you write a basic substitution command with sed?

The basic form is sed 's/old/new/'. It means: find old and replace it with new in each line.

Click to reveal answer
beginner
What does the g flag do in sed 's/old/new/g'?

The g flag means "global". It replaces all occurrences of old in each line, not just the first one.

Click to reveal answer
intermediate
How can you use sed to replace text in a file and save the changes back to the file?

Use the -i option: sed -i 's/old/new/g' filename. This edits the file directly.

Click to reveal answer
intermediate
Why is it useful to use different delimiters in sed substitution, like sed 's|old|new|g'?

Using different delimiters helps when the text contains slashes /. It avoids confusion and makes the command easier to read.

Click to reveal answer
What does the command sed 's/apple/orange/' do?
AAdds 'orange' after 'apple'
BDeletes all 'apple' words
CReplaces the first 'apple' with 'orange' in each line
DPrints lines containing 'apple'
How do you replace all occurrences of 'cat' with 'dog' in a file named pets.txt and save changes directly?
Ased -i 's/cat/dog/g' pets.txt
Bsed 's/cat/dog/g' pets.txt
Csed 's/cat/dog/' pets.txt > pets.txt
Dsed -r 's/cat/dog/g' pets.txt
Why might you use sed 's|path/to/old|path/to/new|g' instead of sed 's/path\/to\/old/path\/to\/new/g'?
ABecause <code>|</code> is faster
BTo avoid escaping slashes <code>/</code> in paths
CBecause <code>/</code> is not allowed in sed
DTo make the command case-insensitive
What happens if you run sed 's/old/new/' without the g flag?
AThe command deletes the line
BAll occurrences of 'old' are replaced
CNo replacement happens
DOnly the first occurrence of 'old' per line is replaced
Which option edits a file without creating a backup when using sed -i?
Ased -i 's/old/new/' file
Bsed -i '' 's/old/new/' file
Csed -i.bak 's/old/new/' file
Dsed 's/old/new/' file
Explain how to use sed to replace all occurrences of a word in a text file and save the changes.
Think about the 's/old/new/g' pattern and how to apply it directly to a file.
You got /4 concepts.
    Describe why choosing different delimiters in sed substitution commands can be helpful.
    Consider when your text contains slashes or other special characters.
    You got /4 concepts.