LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Find and replace text in file (https://www.linuxquestions.org/questions/linux-newbie-8/find-and-replace-text-in-file-4175576436/)

mathewrond 04-01-2016 03:28 PM

Find and replace text in file
 
I have a file with an IP address that I wanted to change with a different IP address. I am using RedHat Linux, could you please let me know how I can do this?


Code:

10.1.1.2:10025      inet  n      -      n      -      -      smtpd
10.1.1.2:10026      inet  n      -      n      -      -      smtpd

I wanted to replace text before :10025 and :10026 with a different IP address. e.g. 10.2.2.5 so the final output in the file is

Code:

10.2.2.5:10025      inet  n      -      n      -      -      smtpd
10.2.2.5:10026      inet  n      -      n      -      -      smtpd

Can anyone help with this?

ardvark71 04-01-2016 04:26 PM

Hi...

I'm guessing this is from a regular text file? If so, simply gain root access (or the root account,) if you don't already have it and use gedit (or another text editor) to open and change the file information as you have shown. :)

One way of doing this is explained here but you could also just double click on the file in question.

Regards...

grail 04-01-2016 05:28 PM

sed would also be a good choice.

WayneB 04-01-2016 08:52 PM

If it's a simple search and replace, this is how it's done.
Code:

sed 's/10.1.1.2/10.2.2.5/g' /etc/hosts
The code above will not make changes to your original file. You're just modifying the output of sed against the file. This is like a preview to check if the results are what you want.

If the code produces the desired output with the new IP change, run the code again with -i to sed to overwrite /etc/hosts.

Code:

sed -i 's/10.1.1.2/10.2.2.5/g' /etc/hosts

frankbell 04-01-2016 09:44 PM

In case it helps, Dave Morriss is doing a series on sed at Hacker Public Radio.

MadeInGermany 04-02-2016 05:35 AM

Regarding the sed solution, the following might be closer to your requirement
Code:

sed 's/[^:]*\(:1002[56]\)/10.1.1.2\1/' file
I.e. restore a part of the search pattern by means of \( \) and its reference \1

John VV 04-02-2016 05:45 PM

open the file in gedit
and click on edit/ find and replace

wpeckham 04-02-2016 06:25 PM

so MANY answers
 
sed can do this, perl can also, gsar is made for such things as well.
You have a simple pattern search and replace, twice. Easy.
Man pages will help, but there are tons of how-to pages on these utilities.

mathewrond 04-03-2016 10:04 PM

Thank you for your suggestion, MadeInGermany. This is exactly what I was looking for.

ardvark71 04-03-2016 11:20 PM

Quote:

Originally Posted by mathewrond (Post 5525821)
Thank you for your suggestion, MadeInGermany. This is exactly what I was looking for.

Glad you got it resolved. :)

Regards...


All times are GMT -5. The time now is 03:55 AM.