Recently in my project, i was supposed to search and replace a text in my project. We all know that grep is the one which is
used to search a word in a file along with some other commands like find, locate etc.. But to search and replace word in a file
sed would be the best option.
What is sed?
A sed is nothing but a stream editor, its something similar to vi or other text manipualting editors that are available in
linux. But the good funcitonlity in sed is that it is capable of searching and replacing a text in a file or some times even
deleting some lines in a text based on their offset or sometimes it is also used as a file manipulating functions such as reading,
writing and appending a file.
It also allows us to pass some set of commands in a file as a script which is used while input is processed. And it also allows to
pass regular expression. you can also combine the sed command with grep to locate and either write or delete or update a file.
Now let us see some basic manipulations using sed command:
a) how to pass a file contents to another file
sed G test.php test2.php
b) how to search and replace a text in a file
sed /s/article/product/g test.php // It searches all the words article and replaces with the word product
c) how to push the changes to another file
sed /s/article/product/g test.php>test2.php // It does the changes and will push the output to another file
d) how to delete some lines in a file
sed 2,3d test.php // It will pass the o/p after deleting the second and third line
you can have lot more functionalities using sed command. For more details and to have a base knowledge, you can look
into this url
I think this may help those who are starting with linux. I really found this interesting. This also works with shell scripts effectively.
Lets learn together