The First Cry of Atom Today is the first day of the rest of my life.

Replace string in command line

In daily development and operation, there are some times to replace string with command line. For example,

$ cat hostlist.txt

These hostlist files usually used by command line tools such as fabric. When you want to deploy other service in, how can we do that? There are command line tools which is very useful and simple for replacing some string.


tr command translates characters. You can replace each one character.

$ cat hostlist.txt | tr "f" "b"

However it seems hard to replace one string not only one character. I think this is the case we usually face. So sed exists.


sed command replace one string, the sequence of character. You can replace foo service to bar service only one command.

$ cat hostlist.txt | sed s/foo/bar/

And also you can use regular expression with sed command.

$ cat hostlist.txt | sed "s/^service[A-Z]/&-&/"

We can use matched string in later place as you like. This is powerful tool for daily operation. Thank you.