Overview of sed
`sed` reads input streams line by line, processes them according to specified rules (scripts), and then sends the results to standard output. By default, the original file is not modified, and to save changes to a file, you need to use redirection (`>`) or the `-i` option.
Main Roles of sed
`sed` is primarily used for the following purposes:
Key Application Areas
- Text Replacement/Substitution: Replaces specific strings within a file with another string. (Most common use case)
- Line Deletion/Additions: Deletes lines that contain specific patterns or inserts new lines at specific locations.
- Pattern Matching and Output: Outputs only lines that match specific patterns or processes only a specific range of lines.
- File Format Changes: Transforms the format of text files or rearranges data.
- Script Automation: Plays a crucial role in shell scripts that batch process large amounts of text files.
Basic Structure of sed
The basic command structure of `sed` is `sed [OPTIONS] 'script' [INPUT_FILE...]`. Here, 'script' takes the form of `[address]command[arguments]`, with the most important command being `s` (substitute).
Key sed Command Options
`sed` provides various options for input processing methods, script specification, output control, and more, allowing for flexible text editing.
1. Script and File Processing Options
2. Substitution (s) Command Flags
3. Other Useful Commands
Generated command:
Try combining the commands.
Description:
`sed` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Learn how to effectively search, replace, and delete content in text files through various usage examples of the `sed` command.
Replace all 'old' with 'new' in a file
sed 's/old/new/g' example.txt
Changes all occurrences of the word 'old' in the `example.txt` file to 'new' and displays the result to standard output.
Directly modify the original file while substituting strings
sed -i.bak 's/DEBUG=true/DEBUG=false/' config.conf
Changes 'DEBUG=true' to 'DEBUG=false' directly in the `config.conf` file while creating a backup of the original file (with a `.bak` extension).
Delete a specific line number
sed '5d' log.txt
Deletes the 5th line from the `log.txt` file and displays the result.
Delete lines within a range
sed '10,20d' document.txt
Deletes the content from the 10th line to the 20th line in the `document.txt` file and displays the result.
Delete lines containing a specific pattern
sed '/WARNING/d' errors.log
Deletes all lines containing the word 'WARNING' in the `errors.log` file and displays the result.
Insert a header line into file contents
sed '1i\Name,Age,City' data.csv
Inserts a new header line above the first line of the `data.csv` file.
Delete empty lines
sed '/^$/d' text.txt
Deletes all empty lines from the `text.txt` file. `^$` is the regular expression that denotes an empty line.