sed
(short for “stream editor”) is a Unix utility designed to parse and transform text using a simple, compact programming language. It was developed between 1973 and 1974 by Lee E. McMahon at Bell Labs and is now available for most operating systems.
The sed
command in Linux is very powerful for parsing and transforming text in a data stream (a file or input from a pipeline). It is commonly used for text manipulation tasks such as searching, finding and replacing, insertion, and deletion.
Using sed for Substitution
Assuming we have the following text file:
$ cat pets.txt
This is my cat
my cat's name is betty
This is my dog
my dog's name is frank
This is my fish
my fish's name is george
This is my goat
my goat's name is adam
Replace the string “my” with “Tony’s”. The following command should be easy to understand (s
represents the substitution command, /my/
represents matching "my", /Tony's/
represents replacing the match with "Tony’s", and /g
indicates replacing all matches in a line):
$ sed 's/my/Tony’s/g' pets.txt
This is Tony’s cat
Tony’s cat's name is betty
This is Tony’s dog
Tony’s dog's name is frank
This is Tony’s fish
Tony’s fish's name is george
This is Tony’s goat
Tony’s goat's name is adam