sed
- The Stream Editor
Summary
sed
is a powerful stream editor that can perform text transformations on input streams (files or input from a pipeline). It is often used for search, replace, delete, and insert operations.
Introduction
sed
(Stream EDitor) is a non-interactive command-line text editor. Unlike interactive editors like vi
or nano
, sed
reads input one line at a time, applies editing commands, and then outputs the result. This makes it highly suitable for automating text manipulation tasks in scripts and pipelines. Its primary function is to perform basic text transformations on an input stream. It operates based on regular expressions, providing flexible pattern matching capabilities.
Use case and Examples
Replace all occurrences of 'apple' with 'orange' in a file
This command reads thefruit.txt
file, replaces all instances of "apple" with "orange" on each line, and prints the modified output to the standard output. The g
flag ensures that all occurrences on each line are replaced, not just the first. Delete lines containing the word 'error'
This command reads thelogfile.txt
file and removes any line that contains the word "error". The output is printed to the standard output. Insert a line 'This is a new line' after each line containing 'important'
This command inserts the text "This is a new line" after every line infile.txt
that contains the word "important". The output is printed to the standard output. Replace the first word of each line with 'NEW'
This command replaces the first word on each line infile.txt
with "NEW". The ^
matches the beginning of the line, [^ ]*
matches a sequence of non-space characters (the first word), and NEW
is the replacement text. Edit a file in place (overwrite the original file)
This command replaces all occurrences of "old_text" with "new_text" infile.txt
and saves the changes directly to the file. Use with caution, as it overwrites the original file. Backups are highly recommended. Commonly used flags
Flag | Description | Example |
---|---|---|
-i | Edit the file in place (overwrite the original file). | sed -i 's/foo/bar/g' file.txt (replaces all 'foo' with 'bar' in file.txt and overwrites the file) |
-n | Suppress automatic printing of pattern space. Useful with p command to print only matched lines. | sed -n '/pattern/p' file.txt (prints only the lines containing "pattern") |
-e | Allows execution of multiple sed commands. | sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt (replaces 'foo' with 'bar' and 'baz' with 'qux' in file.txt) |
-f | Specifies a file containing sed commands. | sed -f commands.sed file.txt (executes the commands in commands.sed on file.txt ) |
-r | Use extended regular expressions. | sed -r 's/(foo|bar)/baz/g' file.txt (replaces 'foo' or 'bar' with 'baz', using extended regex for the | operator) |