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 rememeber 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 stdout or in the commandline only and not actually edit the file.
**-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. **
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
Using sed in vim
: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))
**Converts all lowercase letters to uppercase** throughout the entire file.
### Example:
Before: hello world 123
After: HELLO WORLD 123