sed
(Stream Editor) is a powerful Unix utility used for parsing, transforming, and filtering text in a file or input stream. It works line-by-line and is commonly used in shell scripts for automated editing of configuration files, logs, and other text data. sed
supports advanced operations like substitution, deletion, insertion, and text manipulation using regular expressions.
Command | Purpose |
---|---|
sed 's/old/new/' file.txt |
Replace first occurrence of 'old' with 'new' in each line. |
sed 's/old/new/g' file.txt |
Replace all occurrences of 'old' with 'new' in each line. |
sed -n '5,10p' file.txt |
Print lines 5 to 10 from the file. |
sed '/pattern/d' file.txt |
Delete lines that match the given pattern. |
sed '1d' file.txt |
Delete the first line of the file. |
sed '$d' file.txt |
Delete the last line of the file. |
sed 's/[0-9]//g' file.txt |
Remove all digits from each line. |
sed 's/^/Prefix: /' file.txt |
Add 'Prefix: ' at the beginning of each line. |
sed 's/$/ :Suffix/' file.txt |
Add ' :Suffix' at the end of each line. |
sed -n '/^$/!p' file.txt |
Remove blank lines from the file. |
Tip:
sed
is ideal for one-liners or batch processing of large files in command-line environments.