What are common sed patterns?

QuestionsQuestions8 SkillsProDec, 22 2025
0241

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).
  • $ (Dollar): Matches the end of a line.
    • Example: sed 's/$/./' file (Adds a period to the end of every line).

2. Matching Characters

  • . (Dot): Matches any single character.
    • Example: sed 's/h.t/hit/g' (Matches "hat", "hot", "hbt" and replaces them with "hit").
  • * (Asterisk): Matches zero or more of the preceding character.
    • Example: sed 's/be*/bee/g' (Matches "b", "be", "bee" and replaces them).

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").

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/, use s#old#new# or s|old|new|.
    • Example: sed 's#/usr/bin#/usr/local/bin#g'

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?

0 Comments

no data
Be the first to share your comment!