Sed
sed
(Stream Editor) is a powerful text-processing tool in Unix/Linux that allows you to perform various operations on text files or streams. The most common operation is the substitution (s
) command, but sed
offers many other commands and options. Below are explanations of some common usages:
1. Substitution (s
) Command
s
) CommandThe s
command in sed
is used for substitution, meaning it replaces a specified pattern with another.
Basic Syntax:
Example:
Output:
Common Flags:
g
(global): Replaces all occurrences of the pattern in a line, not just the first one.Output:
n
(specific occurrence): Replaces the nth occurrence of the pattern in a line.Output:
p
(print): Prints the lines where substitutions were made.Output:
i
(ignore case): Makes the search case-insensitive.Output:
2. Delete (d
) Command
d
) CommandThe d
command deletes lines matching a specified pattern.
Example:
Output:
3. Print (p
) Command
p
) CommandThe p
command prints lines matching a pattern. Often used with the -n
flag to suppress automatic printing of lines.
Example:
Output:
4. Insert (i
) Command
i
) CommandThe i
command inserts text before a matching line.
Example:
Output:
5. Append (a
) Command
a
) CommandThe a
command appends text after a matching line.
Example:
Output:
6. Replace Line (c
) Command
c
) CommandThe c
command replaces the entire line matching a pattern.
Example:
Output:
7. Transform (y
) Command
y
) CommandThe y
command works like the tr
command, translating one set of characters to another.
Example:
Output:
8. Multiple Commands (-e
or ;
)
-e
or ;
)You can chain multiple sed
commands together using ;
or the -e
flag.
Example:
Output:
9. Substitute with Shell Variables
You can use shell variables in sed
by wrapping them in double quotes.
Example:
Output:
10. Address Ranges
You can apply sed
commands to specific lines or ranges of lines.
Example:
Output:
Summary
s
: Substitute a pattern with a replacement.g
: Apply substitution globally across the line.d
: Delete matching lines.p
: Print matching lines.i
: Insert text before a line.a
: Append text after a line.c
: Change a matching line.y
: Translate characters.
These are just a few examples of what you can do with sed
. It's a very flexible and powerful tool for text processing.
Last updated