Comprehensive Guide to Using sed for Searching, Deleting, and Replacing Text in Linux
This article explains how to use the Unix stream editor sed for line selection, pattern searching, deletion, and substitution, covering basic syntax, regular‑expression tricks, multiple‑command usage, and in‑place file editing with practical command‑line examples.
sed is a powerful command‑line tool that extends the capabilities of grep by providing both search and replace functions for text streams.
The basic syntax follows the pattern sed -n 'n'p filename , where n denotes the line number to print; -n suppresses automatic output and p explicitly prints matching lines.
Common printing examples include sed -n '5'p test.txt to display line 5, sed -n '1,5'p test.txt for lines 1‑5, and sed -n '1,$'p test.txt to output the whole file.
Pattern searching uses regular expressions, e.g., sed -n '/root/'p 1.txt finds lines containing "root", sed -n '/^l/'p 1.txt matches lines starting with "l", and sed -n '/\/login$/'p 1.txt locates lines ending with "login".
Deletion commands such as sed '1'd file.txt , sed '1,3'd file.txt , and sed '/ab/'d file.txt remove specific lines or lines matching a pattern, while the -i option (e.g., sed -i 's/^/#/g file.txt ) edits the file in place.
Replacement is performed with the s command; examples include sed 's/[0-9]/a/g' 1.txt to replace all digits with "a", sed '1,10s/root/ROOT/g' 1.txt to change "root" to "ROOT" in the first ten lines, and sed -i '30,40s/^.*$/#&/g' 1.txt to comment out a range of lines.
Advanced substitutions use the -r (extended regex) flag and alternate delimiters, such as sed -r 's/([^:]+):(.*):([^:]+)/\3:\2:\1/' file.txt to reorder colon‑separated fields, or sed 's#ot#to#g' file.txt where # replaces the usual / delimiter.
Multiple commands can be chained with -e or a single -r -e expression, for example sed -e '1'p -e '/111/'p -n file.txt or sed -n -r -e '/root/'p -e '/user5/'p file.txt , allowing complex processing in one pass.
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.