fir3net
PPS-Firenetbanner-780.5x190-30-03-17

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

Additional

Further one-liners can be found here

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001