SED Command
SED Command
Knowing how to view certain sections, how to replace words, and how to filter
content from those files. The well-known stream editor is helpful in resolving
these issue.
SED command- stands for stream editor.
1. it can perform various function on file like, searching, find and replace,
insertion or deletion. Most common use of SED command in UNIX is
for substitution or for find and replace.
2. By using SED one can edit files even without opening it, which is much
quicker way to find and replace something in file, than first opening
that file in VI Editor and then changing it.
3.SED is a powerful text stream editor that can do insertion, deletion,
search and replace(substitution).
4. SED command supports regular expression which allows it perform
complex pattern matching.
Several examples---------------------------------------------
Content of a file “myfile.txt”
unix is great operating system.
unix is opensource.
unix is free operating system.
learn operating system.
unix Linux which one you choose.
Unix is easy to learn.
unix is a multiuser os.
Learn unix.
unix is a powerful.
1. Viewing a range of lines of a document
Tools such as head and tail allow us to view the bottom or the top of a file.
What if we need to view a section in the middle? The following command
will return lines 5 through 10 from myfile.txt:
Example: sed -n '5,10p' myfile.txt
2. Replacing or substituting string:
Sed command is mostly used to replace the text in a file. The below
simple sed command replaces the word “unix” with “linux” in the file.
Use the combination of /1, /2 and /g to replace all the patterns from
the nth occurrence of a pattern in a line. The following sed command
replaces the third, fourth, fifth… “unix” word with “linux” word in a line.
Example: $sed 's/unix/linux/3g'myfile.txt
You can restrict the sed command to replace the string on a specific
line number. Here n indicate line number to replace the pattern
The /p print flag prints the replaced line twice on the terminal. If a line
does not have the search pattern and is not replaced, then the /p prints
that line only once.
Here $ indicates the last line in the file. So, the sed command replaces
the text from second line to last line in the file.
SED command can also be used for deleting lines from a particular
file. It is used for performing deletion operation without even opening
the file
Examples: