That's What I Sed

That's What I Sed

sed (Stream EDitor) is a super simple program that can be used to replace text for another in a file. Let’s first view the contents of the file greetings.txt with cat.

$ cat greetings.txt
hello
wilkommen
hola

We can see that the words hello, wilkommen, and hola exist in the text file greetings.txt.

If we wanted to swap out hello for bonjour using sed we could run:

$ sed -i 's/hello/bonjour/' greetings.txt

Running cat greetings.txt will now show:

bonjour
wilkommen
hola

The sed command combined with the -i flag is required to edit a file and switch entire words or expressions. Without the -i flag, sed would only show the word bonjour for hello in stdout only.

Looking at the syntax from the above run sed command, we can see that ’s/hello/ is the word in the document you want to have substituted and bonjour/’ is the word you want to replace it with.

Options for sed

Sometimes when you are editing a file with the substitute flag sed -i s/, you can enter in an additional flag to better refine what you want done.

To uppercase a word or the first letter let’s run

sed -i 's/hola/\u&/' greetings.txt
bonjour
wilkommen
Hola

To do the same thing but uppercase the entire word we would run

sed -i 's/Hola/\U&/' greetings.txt
bonjour
wilkommen
HOLA

The flags \l and \L respectively do the same thing but lowercase the first letter and lowercase all letters.

:smiley: This will also work with vim in COMMAND mode in exactly the same way. Running the /g flag at the end will replace everything in the entire file with the options flag you choose.

:%s/[a-z]/\U&/g))