SED
On this page
- Stream Editor
- Common Examples
- Replace First Occurrence
- Replace Nth Occurrence
- Replace All Occurrences
- Execute Mult Commands
- Using Command File
- Print Only Replaced Lines
- Write Result to File
- Modify Delimiter
- Specify Line Match
- Specify Command Group
- Delete All Lines
- Delete Specific Lines
- Delete Matched Lines
- Insert a Line Before
- Insert a Line After
- Specify Line Insert
- Matched Line Insert
- Insert Multiple Lines
- Modify Line
- Single Char Replace
- Print Specific Lines
- Print Before/After Replacement
- Print Line Number
- Reading from File
Stream Editor
A Stream Text Processor, authored by Lee E. McMahon.
Basic Syntax
OPTIONS
: Command options.command
: Print, replace, delete, etc.file
: The file to process; if omitted, reads from STDIN.
Omitting file
enters interactive mode, executing one line at a time.
Execution Process
- Reading a line of data:
- With a match rule:
- Match successful: Executes related operations.
- Match failed: Prints data as is.
- Without a match rule: Executes related operations.
- With a match rule:
Command Quotes
- Single quotes: Reduces the impact of escape characters, preferably used.
- Double quotes: Can use variable parameters, requires handling special characters.
Common Examples
Replace First Occurrence
Replace the first occurrence of ‘a’ with ‘b’.
Replace Nth Occurrence
Replace the Nth occurrence of ‘a’ with ‘b’.
Replace All Occurrences
Execute Mult Commands
Can use ;
to separate, or use the -e
option.
Using Command File
The cmd.sed
file content is as follows.
Print Only Replaced Lines
-n
indicates suppressing output, p
indicates only outputting matched lines.
Write Result to File
Modify Delimiter
Can use another symbol to replace the command delimiter /
.
Specify Line Match
Match the 2nd line.
Match lines 2-4.
Match lines 2 to the last.
Specify Command Group
Delete All Lines
Delete Specific Lines
Delete Matched Lines
Insert a Line Before
Insert a Line After
Specify Line Insert
Matched Line Insert
Insert Multiple Lines
Must use \
.
Modify Line
Single Char Replace
Print Specific Lines
Print Before/After Replacement
Print Line Number
Reading from File
Create foo and bar files.
Read from the foo file and insert after the first line of bar.
Match string then insert.
Match string, insert, and use d
to delete the matched line.
The following will report a syntax error.
It’s not impossible to do it in one line.