sed
Commandsed
The sed
(stream editor) command is used to process and transform text in a file or input stream. It performs various operations like search, find and replace, insertion, or deletion of text.
sed [OPTIONS] 'command' [file...]
The command
part specifies what text transformations sed
should perform.
sed
sed 's/old/new/' [file]
(Substitute)Replaces the first occurrence of a pattern in each line:
sed 's/old/new/' file.txt
This command replaces the first instance of "old" with "new" in every line of file.txt
.
sed 's/old/new/g' [file]
(Global Substitute)Replaces all occurrences of a pattern in each line:
sed 's/old/new/g' file.txt
This command replaces every occurrence of "old" with "new" globally in each line of the file.
sed 'n d' [file]
(Delete a Line)Delete a specific line in the file:
sed '2d' file.txt
This deletes the second line in file.txt
.
sed '/pattern/d' [file]
(Delete Matching Lines)Delete all lines matching a pattern:
sed '/example/d' file.txt
This deletes all lines that contain the word "example".
sed -n 'p' [file]
(Print Specific Lines)Print specific lines or line ranges:
sed -n '3p' file.txt
This prints only the third line from file.txt
.
sed 'a text' [file]
(Append Text)Append a line of text after a specific line:
sed '3a New line appended' file.txt
This appends the text "New line appended" after the third line.
sed 'i text' [file]
(Insert Text)Insert a line of text before a specific line:
sed '3i Inserted line' file.txt
This inserts "Inserted line" before the third line.
sed 's/old/new/w output.txt' [file]
(Write to File)Write the result of the substitution to another file:
sed 's/old/new/w output.txt' file.txt
This command replaces "old" with "new" and writes the result to output.txt
.
sed '1,3 s/old/new/' [file]
(Range of Lines)Substitute text only within a range of lines:
sed '1,3 s/old/new/' file.txt
This replaces "old" with "new" only in lines 1 to 3.
sed -i 's/old/new/' [file]
(In-place Editing)Modify the original file directly without creating a new one:
sed -i 's/old/new/' file.txt
This replaces "old" with "new" in-place, updating file.txt
directly.
sed --help
Displays help information for the sed
command:
sed --help
Option | Description |
---|---|
sed 's/old/new/' [file] |
Replace the first occurrence of a pattern. |
sed 's/old/new/g' [file] |
Replace all occurrences of a pattern. |
sed 'n d' [file] |
Delete a specific line. |
sed '/pattern/d' [file] |
Delete lines matching a pattern. |
sed -n 'p' [file] |
Print specific lines. |
sed 'a text' [file] |
Append text after a specific line. |
sed 'i text' [file] |
Insert text before a specific line. |
sed 's/old/new/w output.txt' [file] |
Write the result of substitution to a file. |
sed '1,3 s/old/new/' [file] |
Substitute text within a range of lines. |
sed -i 's/old/new/' [file] |
Edit a file in-place. |
sed --help |
Display help information for sed . |
For more detailed information, use the manual page for the sed
command:
man sed