Linux sed Command
Linux sed Command
The sed command in Linux stands for “Stream Editor”. It is used to perform basic text transformations on an input stream (a file or input from a pipeline). sed is extremely powerful for tasks like finding and replacing text, inserting or deleting lines, and more — all done automatically without opening files manually.
It processes text line by line, allowing you to perform automatic edits on files or input streams without manually opening them. It’s especially useful for repetitive text transformations, substitutions, or deletions.
sed Command
- sed is designed for parsing and transforming text.
- It reads text line-by-line and applies operations specified in its command.
- It is widely used for text processing tasks like search, replace, delete, and insert.
- sed can be used directly from the terminal or in shell scripts.
- Changes made by sed are by default temporary unless redirected to a new file.
- Works with regular expressions for pattern matching.
- Does not modify the original file by default (outputs to stdout).
Command Syntax
The general synatx is as follows:
$ sed [options] 'command' filename
Explanation:
- options – Optional flags to modify sed behavior (like
-i
for in-place editing). - command – The sed instruction to perform (like substitute, delete, insert).
- filename – The name of the file on which the sed command will operate.
Examples
Replacing Text
$ sed 's/oldtext/newtext/' filename
Example:
$ sed 's/apple/banana/' fruits.txt
This will replace the first occurrence of “apple” with “banana” in each line of the file fruits.txt.
Replacing All Occurrences in a Line
$ sed 's/oldtext/newtext/g' filename
Example:
$ sed 's/apple/orange/g' fruits.txt
Here, g stands for global, meaning all instances of “apple” in a line will be replaced.
Deleting Lines Containing a Specific Word
$ sed '/word/d' filename
Example:
$ sed '/banana/d' fruits.txt
This will delete all lines containing the word “banana”.
Printing Only Specific Lines
$ sed -n '2,4p' filename
Example:
$ sed -n '2,4p' fruits.txt
This will print only lines 2 to 4 from the file.
sed vs awk
Some of the differences between sed and awk are as follows:
sed | awk | |
---|---|---|
Purpose | Stream editor for simple text transformations | Pattern scanning and processing language |
Focus | Line-by-line editing | Field-by-field data processing |
Complexity | Simple substitutions and deletions | Advanced text processing, calculations, and reports |
Syntax | Compact and simple | More programming-like with variables and control structures |
Use Case Example | Replace words, delete lines | Summarize column data, conditional formatting |