Common Sed Examples

Below are some of the common uses and commands for sed that I have come across over the years,

Find and Replace

sed -i 's|arp|/sbin/arp|g' /etc/init.d/proxyarp

Find and Delete

sed -e '/^$/d' file.txt

Remove Multiple words

This will remove word, word1, or word2 from the file input.txt

sed 's/word\|word1\|word2//g' input.txt

Change the first instance on each line

This will substitute the 1 instance of the word dog for cat on each line.

sed 's/dog/cat/1' newfile.txt

Change case

This will change all the text to uppercase.

 sed -e 's/.*/\U&/g' input.txt

To only change a sub section of text to lower case then the following can be used (this will match everything between the first set of “).

sed -r 's/(^.*".*\" \{)/\L\1/' input.txt

Changing multiple files

Below will change all the files in /etc from word1 to word2.

sed -i 's/word1/word2/g' /etc/*

Insert Line

The following will insert a line with the string “hello” on the 6th line.

sed 6i\hello yourfile.txt

Remove 4 digits

The following will remove 4 digits from the beginning of the line.

sed 's/^[0-9]\{4\}//g' yourfile.txt

String SUB Line contains X but not Y

Substitute string in line that contains X but does not contain Y.

sed '/X/ {/Y/! s/replace/with/}' yourfile.txt
Rick Donato

Want to become a UNIX expert?

Here is our hand-picked selection of the best courses you can find online:
UNIX Administration Fundamentals
Vim Masterclass
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial