The sed
(stream editor) command is a powerful utility in Unix and Linux systems for parsing and transforming text files or input streams. Here are five common and practical uses of sed
that can make your text processing tasks more efficient:
1. Replace Text in a File
You can easily replace a word or pattern in a file using sed
:
sed 's/oldword/newword/g' filename.txt
This replaces all occurrences of oldword
with newword
in filename.txt
. The g
flag at the end means "global" replacement.
2. Delete Lines Matching a Pattern
To delete all lines containing a specific word:
sed '/unwantedword/d' filename.txt
This removes any line that contains unwantedword
from the file.
3. Insert a Line Before a Match
You can insert a line before a matching pattern:
sed '/pattern/i\New line before pattern' filename.txt
This adds "New line before pattern" before any line matching pattern
.
4. Print Specific Line Ranges
To print only a range of lines from a file:
sed -n '5,10p' filename.txt
This prints lines 5 through 10. The -n
suppresses automatic printing, and p
tells sed
to print only the specified lines.
5. Edit a File In-Place
Use the -i
option to modify a file directly:
sed 's/foo/bar/g' -i filename.txt
This replaces all occurrences of foo
with bar
directly in filename.txt
without creating a separate output file.
Conclusion
The sed
command is a lightweight yet incredibly powerful tool for automating text editing tasks. Mastering its options can save you hours of manual editing and help you process large datasets more efficiently.
No comments:
Post a Comment