Replace Particular Word | Expression at a Line in a File with Sed

By | February 15, 2012

I got a question from one of my friend who is doing his engineering here in chennai. The person asks, How do I replace a particular word in a file which is at a particular line number.

Ex: I have a file named “/home/bio” which has following four lines of text.
My name is John, born and brought up in India
John currently lives in India
John has a Mac

Now, line number 3 “John currently lives in India” has to be changed to “John currently lives in USA”. I just want to replace word “India” line 3 with “USA” how do I do that?

SOLUTION: I’m not a Linux GURU to answer this, but I can give you my solution for this problem. Use the following command to get this done.

cat /home/bio | sed -e "3 s/India/USA/" > /tmp/bio; mv /tmp/bio /home/bio

There may be many other ways to do this but this is just one way of doing it.

If you like this article, then please consider sharing it. Sharing really inspires us to do things much better!!

Leave a Reply

Your email address will not be published. Required fields are marked *