sed - macOS


Overview

sed is a powerful stream editor that performs text transformations on an input stream. It is primarily used for searching, replacing, and editing text files in a non-interactive manner, making it an essential tool for scripting and automation tasks.

Syntax

sed [options] 'command' filename(s)

Options/Flags

  • -i: Edit files in-place (without creating a backup).
  • -n: Suppress automatic printing of input lines.
  • -f script-file: Read commands from a script file.
  • -e command: Execute the specified command. Multiple commands can be separated by semicolons (;).
  • -r: Use extended regular expressions.

Examples

Replace “old” with “new” in a text file:

sed 's/old/new/g' file.txt

Insert “added” after line 10:

sed '10a added' file.txt

Delete all lines containing “error”:

sed '/error/d' file.txt

Search and print all lines containing “important”:

sed -n '/important/p' file.txt

Common Issues

  • Incorrect Regular Expressions: Ensure regular expressions are properly formatted and match the intended pattern.
  • File Permissions: Verify that you have sufficient permissions to modify files if using the -i option.
  • Escaping Characters: Properly escape special characters within regular expressions to avoid unexpected behavior.

Integration

  • grep: Use sed to filter input from grep commands.
  • awk: Combine sed with awk for more complex text processing and data extraction.
  • Shell Scripts: Integrate sed into scripts for automated text manipulation.
  • awk
  • grep
  • find