sed

sed: Stream Editor

Sed (Stream Editor) is a powerful command-line utility that allows you to perform complex text manipulation tasks. It’s commonly used for editing files, transforming data, and modifying text within streams of input.

What is sed used for?

  • Text replacement: Replace specific words or patterns with other strings.
  • Pattern matching: Find specific patterns in a file or stream and perform actions on them.
  • Line manipulation: Insert, append, delete, or modify lines in a file.
  • Data transformation: Convert data from one format to another.

Examples of sed usage

  1. Replace all occurrences of „hello“ with „goodbye“:

    bash
    sed 's/hello/goodbye/g' example.txt

  2. Print every line that starts with „error“:

    bash
    sed -n '/^error/ p' example.txt

  3. Delete the second line of a file:

    bash
    sed '2 d' example.txt > newfile.txt

Special sed hacks

  1. Buffered input: Read input from a file and write output to another file without piping:

    bash
    sed -f script.sed <input.txt >output.txt

    This method is faster than using | for piped input.

  2. Regular expressions: Use extended regex syntax by adding the -r or -E flag, which allows you to use more complex patterns:

    bash
    sed -E 's/^(error): (.*)(.*)$/\1 \2/g' example.txt

  3. Context-aware sed scripts: Define a sed script as a file and source it from within another script or command line invocation, allowing you to reuse the same script across multiple commands:

    bash
    sed -f script.sed <input.txt >output.txt
    script.sed:
    s/hello/goodbye/

Who needs sed?

Sed is useful for anyone who works with text on a daily basis. Beginners may find sed overwhelming at first, but as they gain experience and practice using it, they’ll appreciate its power.

Intermediate users will benefit from learning sed’s many features and tricks, while advanced users can take advantage of sed’s ability to perform complex tasks without having to resort to scripting languages like Python or Perl.

Recommended level: Intermediate

No tags for this post.