SED Basics
sed (Stream Editor) is a powerful command-line tool used for text manipulation and transformation. It processes text files line by line and applies specified operations, such as searching, replacing, and deleting.
Basic Syntax
The basic syntax for sed is:
sed [options] 'command' fileoptions: Additional flags to modifysedbehavior.command: The editing operation(s) to perform.file: The input file to process.
If no file is specified, sed reads from standard input.
Common Commands
s: Substitution command (search and replace).d: Delete lines.p: Print lines.a: Append text after a line.i: Insert text before a line.
Useful Options
-i: Edit the file in place (without creating a backup).-n: Suppress automatic printing of lines (useful withpcommand).-e: Allows multiple commands.-f: Execute commands from a file.
Examples
Substitution (Search and Replace)
Replace the first occurrence of "foo" with "bar" on each line:
Replace all occurrences of "foo" with "bar":
Case-insensitive replacement:
Delete Lines
Delete lines containing "error":
Delete the 5th line:
Delete lines from 10 to 20:
Print Lines
Print only lines containing "error":
Print lines 5 to 10:
Insert and Append Text
Insert "Header" before the first line:
Append "Footer" after the last line:
Modify File In-Place
Replace "foo" with "bar" and save changes to the file:
Create a backup of the file before editing:
Combine Multiple Commands
Replace "foo" with "bar" and delete lines containing "baz":
Use a File for Commands
Store commands in a file (commands.sed):
Apply the commands:
Advanced Examples
Replace Only Specific Lines
Replace "foo" with "bar" on lines 2 to 5:
Remove Blank Lines
Add Line Numbers
Summary
sed is a versatile tool for stream editing, offering powerful features for text processing. By mastering its commands and options, you can efficiently manipulate text files and automate complex editing tasks.
Last updated