The sed command, short for Stream Editor, is a powerful command-line tool in Linux used for parsing and transforming text. It operates on input from standard input (stdin) or files and can perform a variety of text manipulation tasks, including search and replace, insertion, deletion, and more.
Basic Syntax
sed [options] 'command' file
Commonly Used Commands
-
Substitution (
s):
Replace occurrences of a pattern with a specified string.sed 's/old/new/g' filename.txtThis replaces all occurrences of "old" with "new" in
filename.txt. -
Delete Lines (
d):
Remove specific lines from the output.sed '2d' filename.txtThis deletes the second line of
filename.txt. -
Print Lines (
p):
Print specific lines to the output.sed -n '1,5p' filename.txtThis prints lines 1 to 5 from
filename.txt. The-noption suppresses automatic printing. -
Insert Lines (
i):
Insert a line before a specific line number.sed '2i\This is a new line' filename.txtThis inserts "This is a new line" before the second line.
-
Append Lines (
a):
Append a line after a specific line number.sed '2a\This is a new line' filename.txtThis appends "This is a new line" after the second line.
-
Change Lines (
c):
Replace a specific line with a new line.sed '2c\This is the new line' filename.txtThis changes the second line to "This is the new line".
Options
-i: Edit files in place (modify the original file).-n: Suppress automatic output; only print lines explicitly specified withp.-e: Allows you to add multiple commands.
Example of Using sed
To replace "foo" with "bar" in a file and save the changes:
sed -i 's/foo/bar/g' filename.txt
Summary
The sed command is a versatile tool for text processing and manipulation in Linux. It is particularly useful for batch editing files and automating text transformations in scripts.
