Chapter 1 · Lesson 11
Intermediate
1 min read
Regular Expressions and sed
Overview
A regular expression describes a text pattern rather than exact text. sed applies text transformations to each input line. It is useful for filtering and scripted replacements, but complex edits should be reviewed before in-place changes.
Detailed Notes
A basic replacement
bash
echo "server=production" | sed 's/production/staging/'
s/production/staging/ means substitute the first production text on each line with staging.
Replace all matches on a line:
bash
echo "one one one" | sed 's/one/two/g'
g means global within each line.
Delete matching lines
bash
sed '/^#/d' config.txt
^# matches a # at the start of a line. d deletes it from the output. The source file is not changed.
Edit in place
bash
cp config.txt config.txt.bak
sed -i 's/127.0.0.1/0.0.0.0/' config.txt
diff -u config.txt.bak config.txt
-i modifies the file. Create a backup and inspect diff before keeping an automated edit.
Regex basics
| Pattern | Meaning |
|---|---|
. | One character, except newline in many regex engines |
* | Repeat previous item zero or more times |
+ | Repeat previous item one or more times |
? | Repeat previous item zero or one time |
^ | Start of line |
$ | End of line |
[0-9] | One digit |
\b | Word boundary, engine-dependent |
Test an expression interactively and match one file at a time before bulk edits.
Common Interview Questions
Finished this lesson?
0 of 25 lessons done · 0% of the course

