Posted: . At: 10:50 AM. This was 5 years ago. Post ID: 12858
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


Search and replace text in a file with ed.


I have a text file containing this string.

deusexmachina:Documents jason$ cat out 
Darwin deusexmachina.local 18.2.0 Darwin Kernel Version 18.2.0: Mon Nov 12 20:24:46 PST 2018; root:xnu-4903.231.4~2/RELEASE_X86_64 x86_64

And I want to replace one instance of the word Darwin with Linux.

This is very easy to do with ed.

deusexmachina:Documents jason$ ed out
138
1,$s_Darwin_Linux
Linux deusexmachina.local 18.2.0 Darwin Kernel Version 18.2.0: Mon Nov 12 20:24:46 PST 2018; root:xnu-4903.231.4~2/RELEASE_X86_64 x86_64
wq
137

Even the very old ed line editor has a regex function and can replace a word in a string. This is not the best solution, but I just found this out and I thought that it might be useful to someone.

This is a better way, using the sed stream editor.

deusexmachina:Documents jason$ sed 's/Darwin/Linux/' out
Linux deusexmachina.local 18.2.0 Linux Kernel Version 18.2.0: Mon Nov 12 20:24:46 PST 2018; root:xnu-4903.231.4~2/RELEASE_X86_64 x86_64

Yet another way to make changes to a file is with VIM. Run this simple one-liner to change words in a file.

deusexmachina:Documents jason$ ex -s -c '%s/Kernel/Windows/g|x' out
deusexmachina:Documents jason$ cat out 
Linux deusexmachina.local 18.2.0 Darwin Windows Version 18.2.0: Mon Nov 12 20:24:46 PST 2018; root:xnu-4903.231.4~2/RELEASE_X86_64 x86_64

This changes the word “Kernel” in the file to “Windows”.

It is also possible to replace text in a pipe from another program.

deusexmachina:Documents jason$ uname -a | awk '{sub(/deusexmachina/,"Amiga")}1'
Darwin Amiga.local 18.2.0 Darwin Kernel Version 18.2.0: Mon Nov 12 20:24:46 PST 2018; root:xnu-4903.231.4~2/RELEASE_X86_64 x86_64

The awk utility makes this very easy.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.