Identify IP address from a text file and replace it with new address.

C

Chandu80

Hello All,
I want to write a script by which I can open up a text file,scan
through it,find the line which contains the word 'test_site',get the
IP address corresponding to that word, replace that IP with another IP
address and then save and close the file.
Are there any commands in Ruby to identify IP address from a string?


Thanks in advance


Regards
Chandrika
 
A

Alexey Bovanenko

[Note: parts of this message were removed to make it a legal post.]

Hi!

I think you can use the following code:

text=IO.read(filename_of_file_with_ip)
text.gsub!(/test_site\s*\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/i,"0.0.0.0") #
0.0.0.0 - it's my new ip
f=File.new("outtxt","w")
f.write(text)
f.close
 
Z

zuerrong

2010/11/8 Chandu80 said:
Hello All,
I want to write a script by which I can open up a text file,scan
through it,find the line which contains the word 'test_site',get the
IP address corresponding to that word, replace that IP with another IP
address and then save and close the file.
Are there any commands in Ruby to identify IP address from a string?

maybe a regex is useful, though that's not rigorous enough.

irb(main):001:0> s=3D"ip addr:12.34.56.78"
=3D> "ip addr:12.34.56.78"

irb(main):002:0> s.scan /\d+\.\d+\.\d+\.\d+/
=3D> ["12.34.56.78"]


--=20
Kind regards,
=C2=A0 =C2=A0 =C2=A0Zuer (=E7=A5=96=E5=84=BF)
 
C

Chandu80

[Note:  parts of this message were removed to make it a legal post.]

Hi!

I think you can use the following code:

text=IO.read(filename_of_file_with_ip)
text.gsub!(/test_site\s*\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/i,"0.0.0.0") #
0.0.0.0 - it's my new ip
f=File.new("outtxt","w")
f.write(text)
f.close



Hello All,
I want to write a script by which I can open up a text file,scan
through it,find the line which contains the word 'test_site',get the
IP address corresponding to that word, replace that IP with another IP
address and then save and close the file.
Are there any commands in Ruby to identify IP address from a string?
Thanks in advance
Regards
Chandrika

Hi,
Thanks for the response.It did work.However isn't there a provision to
edit the same file and save it?

Regards
Chandrika
 
R

Robert Klemme

Thanks for the response.It did work.However isn't there a provision to
edit the same file and save it?

ruby -p -i.bak -e 'gsub /\d{1,3}(?:\.\d{1,3}){3}/, "XX.XX.XX.XX"' a_file

If you omit ".bak" there is no backup. Please see "ruby -h".

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top