0
votes

I have a file where i store the output of tnsping this file will contain text as:

TNS Ping Utility for 32-bit Windows: Version 10.1.0.4.2 - Production on 12-AUG-2013 11:28:33

Copyright (c) 1997, 2003, Oracle.  All rights reserved.

Used parameter files:
D:\oracle\Home_1\network\admin\sqlnet.ora


Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST =10.184.10.90)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = ORCL)))
OK (0 msec)

I need to extract value of HOST, PORT, SERVICE_NAME through Batch file. The value I am expecting is 10.184.10.90 for HOST, 1521 for PORT and ORCL for SERVICE_NAME.

Sujit

2

2 Answers

0
votes

This filters the line containing the word "Attempting" and splits it up into tokens separated by the delimiters ) = and a space

You can count the tokens from the left end of the line and the 9th, 11th and 14th section of the line, which are separated by ")= " are the items which you want in the variables. Each token is applied to %%a %%b %%c in order.

Remove the echo sections and they will set the variables.

@echo off
for /f "tokens=9,11,14 delims=)= " %%a in ('type "file.txt" ^| find "Attempting"') do (
echo set "HOST=%%a"
echo set "PORT=%%b"
echo set "SERVICE_NAME=%%c"
)
pause

To describe the tokens:

If you have a string like this =abc = def=ghi and you apply delimiters of a space and equals = then the sections that are left are "abc" "def" "ghi" (without the quotes) and they call the sections 'tokens'. If you use tokens=2 then %%a in this case will be set to def

Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST =10.184.10.90)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = ORCL)))

This line above from the original example when using delims of )= and space, will have the tokens below, and if you count them then the IP address is the 9th token. Note that the delimiters of )= and space have vanished, as that is the purpose of the delimiters.

Attempting
to
contact
(DESCRIPTION
(ADDRESS
(PROTOCOL
TCP
(HOST
10.184.10.90
(PORT
1521
(CONNECT_DATA
(SERVICE_NAME
ORCL

I hope that is clear.

0
votes
@ECHO OFF &SETLOCAL
FOR /f "delims=" %%a  IN ('findstr "Attempting to contact" "file"') DO SET "line=%%a"
SET "line=%line:*HOST=%"
FOR /f "tokens=2delims==)" %%a IN ("%line%") DO FOR %%b IN (%%a) DO SET "host=%%b"
SET "line=%line:*PORT=%"
FOR /f "tokens=2delims==)" %%a IN ("%line%") DO FOR %%b IN (%%a) DO SET "port=%%b"
SET "line=%line:*SERVICE_NAME=%"
FOR /f "tokens=2delims==)" %%a IN ("%line%") DO FOR %%b IN (%%a) DO SET "SERVICE_NAME=%%b"
ECHO HOST:%host% PORT:%port% SERVICE_NAME:%SERVICE_NAME%

Better to use sed for this.