Skip to main content

sed

sed, short for "stream editor", is a powerful and versatile text processing tool available on Unix, Linux, and similar operating systems. It's primarily used for parsing and transforming text in a stream (i.e., a file or input from a pipeline).

Key Features

  1. Pattern Matching: sed uses regular expressions, allowing complex pattern matching and replacement.

  2. In-place Editing: Capable of editing files in-place without the need to redirect the output to a new file.

  3. Scriptable: Can be used in shell scripts, making it ideal for automating text manipulation tasks.

  4. Line-by-Line Processing: Processes input line by line, applying specified operations to each line.

Basic Syntax

The basic syntax of the sed command is:

sed [options] 'command' file

Where command specifies what sed should do (like substitution), and file is the name of the file to be processed.

Examples

  1. Find and Replace Text

    • Replace the first occurrence of 'old' with 'new' in a file:

      sed 's/old/new/' filename
    • Replace all occurrences of 'old' with 'new' in a file:

      sed 's/old/new/g' filename
    • Replace text with regular expressions:

      sed 's/^.*old.*$/new/g' filename

      This replaces the entire line containing 'old' with 'new'.

  2. In-Place Editing

    • To edit the file in-place and save changes back to the file:

      sed -i 's/old/new/g' filename
  3. Delete Lines

    • Delete a specific line (e.g., the 2nd line):

      sed '2d' filename
    • Delete lines matching a pattern:

      sed '/pattern_to_match/d' filename
  4. Print Specific Lines

    • Print a specific line (e.g., line 4):

      sed -n '4p' filename
    • Print lines matching a pattern:

      sed -n '/pattern/p' filename
  5. Append/Insert Text

    • Append a line after a match:

      sed '/pattern/a new_line_text' filename
    • Insert a line before a match:

      sed '/pattern/i new_line_text' filename
  6. Multiple Commands

    • Execute multiple sed commands:

      sed -e 'command1' -e 'command2' filename
    • Example: Replace 'old' with 'new' and then delete lines containing 'delete_this':

      sed -e 's/old/new/g' -e '/delete_this/d' filename

Advanced Usage

  • Range Selection: sed can process a range of lines. For example, sed '2,5d' filename deletes lines 2 to 5.

  • Hold and Get from Buffer: sed offers a hold buffer for storing and retrieving lines, enabling more complex editing scenarios.

  • Case Insensitivity: Adding an I at the end of the substitute command makes the match case insensitive.

Conclusion

sed is a powerful stream editor used for text manipulation and transformation. Its ability to use regular expressions and scriptable nature makes it a go-to tool for text processing in Unix-like environments. The examples provided demonstrate some of the basic and advanced uses of sed, showcasing its versatility in handling various text processing tasks.