The sed or stream editor command is a program that you can use to modify text files according to various parameters. The sed command can also be used for global search and replace actions. Some of the common command options and their uses are given in the following table.
Option | Description |
---|---|
-d | Delete the lines that match a specific pattern or line number. |
-n,p | Print only the lines that contain the pattern. |
s | Substitute the first occurrence of the string in the file. |
S,g | Globally substitute the original string with the replacement string for each occurrence in the file. |
Syntax
The general syntax of the sed command is:
# sed {'option/address/ action'} {file names}
Addresses tell sed to act only on certain lines or to act only on text that matches a given regular expression pattern. They are optional. Addresses are followed by the action to be performed when a match is found. The last argument is the name of the input file. The option, address, and action parameters are typically enclosed within single quotation marks.
If you encounter the below error while running the sed command:
sed: command not found
you may try installing the below package as per your choice of distribution:
OS Distribution | Command |
---|---|
Debian | apt-get install sed |
Ubuntu | apt-get install sed |
Alpine | apk add sed |
Arch Linux | pacman -S sed |
Kali Linux | apt-get install sed |
CentOS | yum install sed |
Fedora | dnf install sed |
Raspbian | apt-get install sed |
sed Command Examples
1. Replace the first occurrence of a regular expression in each line of a file, and print the result:
# sed 's/regular_expression/replace/' filename
2. Replace all occurrences of an extended regular expression in a file, and print the result:
# sed -r 's/regular_expression/replace/g' filename
3. Replace all occurrences of a string in a file, overwriting the file (i.e. in-place):
# sed -i 's/find/replace/g' filename
4. Replace only on lines matching the line pattern:
# sed '/line_pattern/s/find/replace/' filename
5. Delete lines matching the line pattern:
# sed '/line_pattern/d' filename
6. Print the first 11 lines of a file:
# sed 11q filename
7. Apply multiple find-replace expressions to a file:
# sed -e 's/find/replace/' -e 's/find/replace/' filename
8. Replace separator `/` by any other character not used in the find or replace patterns, e.g. `#`:
# sed 's#find#replace#' filename