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 a file I made called 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
The way I remember the order of the syntax is by reading it out loud. I will be substituting (s) the word hello with the word bonjour.
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 stdoute only and not actually edit the file.
From the sed help page:
-i[SUFFIX], --in-place[=SUFFIX]: edit files in place (makes backup if extension supplied). The default operation mode is to break symbolic and hard links. This can be changed with --follow-symlinks and --copy.
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 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
Using sed in vim
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/hello/bonjour/g
Explanation:
:%s: Apply substitution to the entire file.
g: Global replacement (replace all occurrences in each line).
:%s/[a-z]/\U&/g))
**Converts all lowercase letters to uppercase** throughout the entire file.
### Example:
Before: hello world 123
After: HELLO WORLD 123