The `sed` (Stream Editor) command is a powerful tool in Linux for editing and manipulating text files. It allows you to perform tasks like searching, replacing, inserting, and deleting text within files using a simple command-line interface.
`sed` stands for Stream Editor. It reads input from a file or standard input, processes it line by line, and outputs the results. It's commonly used for text transformation and automation in shell scripts.
The basic syntax of `sed` is:
sed [options] 'command' filename
- options are flags like `-i` (in-place editing), `-n` (suppress automatic output), etc.
- command is the action you want to perform (e.g., replace, insert, delete).
- filename is the name of the file you want to edit.
To replace all occurrences of a word in a file:
sed 's/old/new/g' filename.txt
- s stands for substitute.
- old is the text you want to replace.
- new is the text you want to replace it with.
- g stands for global (replace all occurrences in the line).
To replace text in multiple files:
sed -i 's/old/new/g' file1.txt file2.txt
The -i option edits the file in-place.
To delete lines matching a pattern:
sed '/pattern/d' filename.txt
- /pattern/d deletes all lines that match the pattern.
To insert text at the beginning of a file:
sed '1i\This is a new line' filename.txt
- 1i inserts text before line 1.
- You can also use i to insert at the top of the file.
To append text at the end of a file:
< ode>sed '$a\This is a new line at the end' filename.txt
- $a appends text after the last line.
`sed` supports regular expressions for more complex replacements:
sed 's/[0-9]/X/g' filename.txt
This replaces all digits with the letter "X".
You can replace multiple patterns in a single command:
sed -e 's/old1/new1/g' -e 's/old2/new2/g' filename.txt
Replace all instances of "hello" with "hi" in example.txt:
sed 's/hello/hi/g' example.txt
Replace "old" with "new" in all .txt files:
sed -i 's/old/new/g' *.txt
Delete all lines with the word "error" in log.txt:
sed '/error/d' log.txt
Insert a line at the top of file.txt:
sed '1i\This is the new line' file.txt
Combine `sed` with `grep` to filter and modify text:
grep 'pattern' filename.txt | sed 's/pattern/replacement/g'
`sed` is often used in shell scripts for automation:
#!/bin/bash
sed -i 's/old/new/g' file.txt
echo "Text replaced in file.txt"
The `sed` command is a powerful tool for text manipulation in Linux. Whether you're replacing text, deleting lines, or inserting content, `sed` provides a flexible and efficient way to handle these tasks from the command line. With practice, you'll find it to be one of the most useful commands in your Linux toolkit.