Prepared by: Anwer Sadath Abdhul Muttaliff
sed
(stream editor) is a powerful command-line tool for text processing. It allows you to manipulate and transform text in streams or files efficiently. This guide covers basic to advanced sed
operations, with practical examples for system administrators and developers.
sed [options] 'script' inputfile
g
).Replace the first occurrence of oldtext
with newtext
:
sed 's/oldtext/newtext/' file.txt
Replace all occurrences in a line with the g
flag:
sed 's/oldtext/newtext/g' file.txt
By default, sed
outputs changes to the console. To save changes, use -i
:
sed -i 's/oldtext/newtext/' file.txt
Delete specific lines (e.g., line 3):
sed '3d' file.txt
Delete lines matching a pattern:
sed '/pattern/d' file.txt
Print only lines 5 to 10:
sed -n '5,10p' file.txt
Replace all digits with #
:
sed 's/[0-9]/#/g' file.txt
Insert before line 2:
sed '2i\This is inserted text' file.txt
Append after line 2:
sed '2a\This is appended text' file.txt
Replace multiple patterns in one command:
sed -e 's/foo/bar/' -e 's/baz/qux/' file.txt
Convert lowercase to uppercase:
sed 's/[a-z]/\U&/g' file.txt
Replace settings in multiple .conf
files:
sed -i 's/old_setting/new_setting/' *.conf
Remove sensitive data (e.g., IP addresses):
sed -r 's/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/REDACTED/g' log.txt
Update usernames in /etc/passwd
:
sed -i 's/old_user/new_user/' /etc/passwd
Automate renaming files in a directory:
for file in *.txt; do
sed -i 's/foo/bar/' "$file"
done
sed
is an indispensable tool for text processing and automation in Linux. Whether you're performing simple search-and-replace operations or managing complex configurations, sed
offers a powerful and efficient solution. By mastering these techniques, you can streamline your workflow and enhance your productivity as a system administrator or developer.