The Linux command SED stands for stream editor, and its use to do lot’s of operation on file for search, find and replace, insert new text, and delete after seeing the pattern.
The most common use of SED command which a System administrator or engineer doing every day is text substitution or find and replace text.
Why is SED command essential to find and replace text as we can do it in vi, vim editor quickly? Well, the answer is, the SED command do these operations easily without opening the file, which is more important when you are dealing with data in a script or within any extensive process where text replacement is a small part of your whole automated task.
sed OPTIONS... [SCRIPT] [INPUTFILE...]
Suggested Reading: Linux sed command Structure
We will use below created file as an input for sample command
$cat > linuxconcept.txt Linux is most popular os. Linux is opensource and free os. Learn Linux operating system. which one you choose for learning Linux or UNIX. Linux is easy to learn. Linux is a multiuser os. Learn Linux. Linux is a powerful OS.
Replacing or Substituting string is find string in a file and replacing that string with another one.
The below command will help you to substitute string in file “linuxconcept.txt” without open the file.
$sed 's/Linux/UNIX/' linuxconcept.txt Output: UNIX is most popular os. Linux is opensource and free os. Learn UNIX operating system. which one you choose for learning UNIX or UNIX. UNIX is easy to learn. Linux is a multiuser os. Learn Linux. Linux is a powerful OS.
Here in the above command, “s” is indicating SED command used for substituting string, and “/” is used as delimiters. The text “Linux” is a search pattern here, and the “UNIX” is replacement string.
In default SED command only replace the first occurrence of a string in each line and not replacing the string if it comes in second, third …. times in the same line.
Replacing all the occurrence in file
To replace all find string in a file, you can use the “/g” substitute flag in command, here “g” is for “global” substitution.
$sed 's/Linux/UNIX/g' linuxconcept.txt Output: UNIX is most popular os. UNIX is opensource and free os. Learn UNIX operating system. which one you choose for learning UNIX or UNIX. UNIX is easy to learn. UNIX is a multiuser os. Learn UNIX. UNIX is a powerful OS.