The sed
command stands for “stream editor.” It is used to perform basic text transformations on an input stream. The sed
command is commonly used for text substitution, filtering, and other text processing tasks.
Initial Example
Using sed
to replace the first occurrence of the word “old” with “new” in a file called file.txt
:
sed 's/old/new/' file.txt
SED Command
Parameter | Description |
---|---|
-n, --quiet, --silent | Suppress automatic output printing, only print lines explicitly specified |
--debug | Output detailed execution steps for debugging purposes |
-e script, --expression=script | Add the provided script to the list of commands to be executed |
-f script-file, --file=script-file | Execute commands from the specified script file |
--follow-symlinks | Follow symbolic links when making in-place edits |
-i[SUFFIX], --in-place[=SUFFIX] | Edit files directly, optionally making a backup with the given suffix |
-l N, --line-length=N | Set the maximum line length for the l command, wrapping lines as needed |
--posix | Disable all GNU-specific extensions |
-E, -r, --regexp-extended | Use extended regular expressions for pattern matching (POSIX -E for portability) |
-s, --separate | Treat each file as a separate input stream, rather than a single continuous stream |
--sandbox | Run in sandbox mode, disabling the e , r , and w commands for security |
-u, --unbuffered | Minimize input buffering and flush output buffers more frequently |
-z, --null-data | Use NUL characters to separate lines of input instead of newline characters |
--help | Show help information and exit |
--version | Display version information and exit |
Examples
1. Basic Text Substitution
To replace the first occurrence of “old” with “new” in each line of a file:
sed 's/old/new/' filename.txt
2. Global Text Substitution
To replace all occurrences of “old” with “new” in each line of a file:
sed 's/old/new/g' filename.txt
3. In-Place Editing
To perform text substitution directly in the file (without creating a new file):
sed -i 's/old/new/g' filename.txt
4. Deleting Lines
To delete lines that match a specific pattern:
sed '/pattern/d' filename.txt
5. Printing Specific Lines
To print only the lines that match a specific pattern:
sed -n '/pattern/p' filename.txt
6. Replace on a Specific Line
To replace text on a specific line number (e.g., line 3):
sed '3s/old/new/' filename.txt
7. Using Regular Expressions
To use regular expressions for more complex text manipulation:
sed 's/[0-9]/#/g' filename.txt
8. Append Text After a Match
To append text after lines that match a specific pattern:
sed '/pattern/a\new text' filename.txt
9. Insert Text Before a Match
To insert text before lines that match a specific pattern:
sed '/pattern/i\new text' filename.txt