sed Command
The sed (stream editor) command is a powerful text processing tool that can perform basic text transformations on an input stream (a file or input from a pipeline). It is commonly used for finding and replacing text, deleting lines, inserting content, and more.
Syntax
Description
sed is a non-interactive stream editor. It receives text input, performs operations (like searching, finding, replacing, inserting, deleting) based on a script, and then outputs the transformed text. It does not modify the original file unless explicitly told to do so with the -i option.
Common uses include:
- Find and replace text using regular expressions
- Delete specific lines or ranges of lines
- Insert or append content to lines
- Transform text streams from pipelines
Common 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) |
-r, --regexp-extended |
Use extended regular expressions in the script |
-s, --separate |
Consider files as separate rather than as a single continuous stream |
Examples
Replace all occurrences of a string
Replaces all occurrences of 'old_text' with 'new_text' in filename.txt and prints to standard output.
Replace in place (with backup)
Replaces all occurrences of 'old_text' with 'new_text' directly in filename.txt, creating a backup file named filename.txt.bak.
Delete lines containing a pattern
Deletes all lines containing 'pattern' from filename.txt and prints the result.
Print specific lines by number
Prints only the 5th line of filename.txt.
Insert a line before a pattern
Inserts 'New line to insert' before each line containing 'pattern'.
Append a line after a pattern
Appends 'New line to append' after each line containing 'pattern'.