In sed, patterns are usually defined using Regular Expressions (Regex). Here are some of the most common patterns you will use to manipulate text:
1. Matching the Start and End of a Line
^(Caret): Matches the start of a line.- Example:
sed 's/^/Starting: /' file(Adds "Starting: " to the beginning of every line).
- Example:
$(Dollar): Matches the end of a line.- Example:
sed 's/$/./' file(Adds a period to the end of every line).
- Example:
2. Matching Characters
.(Dot): Matches any single character.- Example:
sed 's/h.t/hit/g'(Matches "hat", "hot", "hbt" and replaces them with "hit").
- Example:
*(Asterisk): Matches zero or more of the preceding character.- Example:
sed 's/be*/bee/g'(Matches "b", "be", "bee" and replaces them).
- Example:
3. Character Classes
[ ](Brackets): Matches any one character inside the brackets.- Example:
sed 's/[0-9]/X/g'(Replaces every digit with "X"). - Example:
sed 's/[a-z]/L/g'(Replaces every lowercase letter with "L").
- Example:
4. Deleting Lines
You can use patterns with the d command to remove lines:
- Delete blank lines:
sed '/^$/d' filename - Delete lines containing a word:
sed '/temporary/d' filename
5. Using Alternate Delimiters
As mentioned in your lab, if you are working with paths (which contain many /), you can change the character used for the pattern:
- Instead of
s/old/new/, uses#old#new#ors|old|new|.- Example:
sed 's#/usr/bin#/usr/local/bin#g'
- Example:
Summary Table
| Pattern | Meaning |
|---|---|
^ |
Start of line |
$ |
End of line |
. |
Any single character |
[a-zA-Z] |
Any letter |
[0-9] |
Any digit |
\< |
Start of a word |
\> |
End of a word |
Would you like to try practicing one of these patterns on your sed_test.txt file?