Gabil
Gabil

Reputation: 31

Extracting IP addresses from text file with batch

I have a text file with data like this:

Aug 21 [10.23.5.5] Teardown dynamic

Aug 18 [10.150.1.45] Aug 21 15:28:34 otoldc

Aug 24 [10.96.5.10] Aug 21 2012 18:58:26 HYD

Aug 24 [10.96.5.10] Aug 22 2012 18:58:26 HYD

Aug 21 [192.168.15.231] sendmail[18831]

I need to remove everything except IP addresses surrounded by "[" and "]". String length before "[" is fixed. String length after "]" varied. I tried use one of existing solutions here but couldn't get success. Is it possible to do it using batch? Thanks:-)

Upvotes: 0

Views: 5044

Answers (3)

wmz
wmz

Reputation: 3685

directly from command line: for /f "tokens=2 delims=[]" %F in (file.txt) do echo %F. Redirect as you wish. Not as flexible as sed/awk & regexes, but it does not require external tools.

If you plan to put together something more complex though, I would really look to more powerful tools - apart from already mentioned awk or Perl natural choice on Win would be Powershell.

Upvotes: 2

cas
cas

Reputation: 735

Install a version of sed if it's not already on your system.

$ sed -r -e 's/^[^[]*\[([^]\]*)].*/\1/' file.txt
10.23.5.5
10.150.1.45
10.96.5.10
10.96.5.10
192.168.15.231

This sed one-liner 'script' outputs each input line after removing everything from the lines except the contents inside the first set of [] square brackets on the line - it does not check those contents to make sure it matches an IP address.

Upvotes: 1

Adam Eberlin
Adam Eberlin

Reputation: 14205

You tagged this as batch, so I assume this is on Windows and not linux. All the same, I'd highly recommend you head over to Cygwin's website and download a copy. This will give you access to the cat and grep commands, which make this much simpler. Once you have Cygwin installed, you can run the following command to parse out the IP addresses from your log file.

cat your.log | grep -oE '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' > ips.txt

Cheers

Upvotes: 0

Related Questions