Categories
Linux regex

Sed 101

SED aka stream editor is a utility app in linux / bsd systems (among others) which allows you to parse text in files based on simple regexp and change them based on its own set of rules.

simple syntax for parsing and replacing text in a file called test.txt that contains the text I love cats and hate dogs n number of times and replace with I love sloths and hate ducks

sed -e 's/cats/sloths/' test.txt
sed -e 's/dogs/ducks/' test.txt

but to make it shorter you can actually add the options to same command.

sed -e 's/cats/sloths/g' -e 's/dogs/ducks/g' test.txt

the problem with above? it will only do so once per line, so if oyu have multiple instances it wont work. so you need to “globalize” this search/replace. note the added g after the words

sed -e 's/dogs/ducks/g' test.txt

what if you only want the replacements to happen on lines 2 – 7?

sed -e '2,7s/dogs/ducks/g' test.txt

How about if you want to only replace on lines begining with the word link? (replace link with any other word you please) and ending in the word pie (again replace pie with whatever)

sed -e '/^link/,/^pie/s/dogs/ducks/g' test.txt

what if your words have the separator / already in them? say in a path like /home/kingpin ? well you can replace the separator with anything arbitrary you choose at the beginning after the s and it will change the separator all throughout the sed command.

sed -e 's;dogs;ducks;g' test.txt

or with / in the words

sed -e 's;/home/kingpin;/home/notkingpin;g' test.txt

 

Well this is it for now… theres SO much more out there, tye man sed in your CLI to find out more or just google 🙂