sed
is a stream editor in Linux that is used to perform basic text transformations on an input stream (a file or input from a pipeline). This guide will provide examples of how to use the sed
command.
Syntax
The basic syntax of the sed
command is as follows:
$ sed [options] 'command' file
options
: optional flags to modify the behavior of thesed
command.command
: the text transformation to be performed.file
: the input file to be edited (or omitted for standard input).
Basic Usage
Replacing text
One of the most common uses of sed
is to replace text in a file. To replace a string in a file, the following syntax is used:
$ sed 's/old-text/new-text/g' file
The s
indicates that we are using the substitution command, old-text
is the text to be replaced, new-text
is the text to replace it with, and the g
at the end indicates that all occurrences of old-text
should be replaced (without g
, only the first occurrence in each line would be replaced).
Printing specific lines
$ sed -n '3,5p' file
This will print lines 3 to 5 from the file. The -n
option tells sed
to only print the specified lines and not all lines in the file.
Advanced Usage
Using Regular Expressions
sed
supports basic regular expressions, which can be used to match and replace text based on patterns. The following example shows how to use a regular expression to replace all occurrences of a number in a file:
$ sed 's/[0-9]/X/g' file
This will replace all occurrences of numbers in the file with the letter X
.
Deleting Lines
You can use sed
to delete specific lines from a file. The following syntax will delete lines 3 to 5:
$ sed '3,5d' file
Inserting Lines
You can also insert new lines into a file using sed
. The following syntax will insert a new line after line 3:
$ sed '3a\This is a new line' file
Appending Text
You can append text to the end of a file using sed
. The following syntax will append the text This is some text
to the end of the file:
$ sed '$a\This is some text' file
Conclusion
In this guide, we covered the basic and advanced usage of the sed
command in Linux. With these examples, you should be able to perform a variety of text transformations on your files.