sed
Quick Reference
Command Name:
sed
Category:
text processing
Platform:
linux
Basic Usage:
Common Use Cases
- 1
Text editing
Perform search and replace operations on text data
- 2
Data transformation
Transform and modify data in various formats
- 3
Scripting
Use in shell scripts to edit text data programmatically
- 4
Configuration files
Modify configuration files automatically
Syntax
sed [OPTION]... {script} [input-file]... sed [OPTION]... -f script-file [input-file]...
Options
Option | Description |
---|---|
-n, --quiet, --silent | Suppress automatic printing of pattern space |
-e script, --expression=script | Add the script to the commands to be executed |
-f script-file, --file=script-file | Add the contents of script-file to the commands to be executed |
-i[SUFFIX], --in-place[=SUFFIX] | Edit files in place (makes backup if SUFFIX supplied) |
-l N, --line-length=N | Specify the desired line-wrap length for the 'l' command |
-E, -r, --regexp-extended | Use extended regular expressions in the script |
-s, --separate | Consider files as separate rather than as a single, continuous long stream |
--follow-symlinks | Follow symlinks when processing in place |
-z, --null-data | Separate lines by NULL characters |
--help | Display a help message and exit |
--version | Output version information and exit |
Examples
How to Use These Examples
The examples below show common ways to use the sed
command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.
Basic Examples:
sed 's/old/new/' file.txt
Replaces the first occurrence of "old" with "new" on each line of file.txt. This is the most basic substitution form of sed, using the 's' command for substitution.
sed 's/old/new/g' file.txt
Replaces all occurrences of "old" with "new" in file.txt. The 'g' flag (global) makes sed replace all matches, not just the first one on each line.
sed -i 's/old/new/g' file.txt
Edits file.txt in-place, replacing all occurrences of "old" with "new". The -i option modifies the file directly instead of printing to standard output.
sed '5d' file.txt
Deletes the 5th line from file.txt. The 'd' command indicates deletion, and the '5' is an address that specifies which line to operate on.
Advanced Examples:
sed -n '5,10p' file.txt
Prints only lines 5 through 10 from file.txt. The -n option suppresses default printing, and the 'p' command prints the lines in the specified range.
sed '/^#/d' config.txt
Deletes all lines that start with # in config.txt. This uses a regular expression (^#) to match lines beginning with a hash character, which is useful for removing comments from configuration files.