Get the tnsnames.ora alias for a given service name

Hello,

puzzling me now way to long....so hopefully someone has the answer at hand:
The following shows a sample tnsnames.ora from another topic.
What I want to get as result the tnsnames alias "PRI" when searching for the service name pri.
That is, the left hand side of the tnsnames entry where the service name 'pri' is used.
Preferably shell script or sed.

PRI =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 10.0.3.7)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = pri)
      (INSTANCE_NAME = pri)
    )
  )

STDBY =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 10.0.3.5)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = stdby)
      (INSTANCE_NAME = stdby)
    )
  )

any help appreciated

tags: linux, tnsnames, tnsname alias, service name

Like the following shell command with embedded awk script?

awk '
  $2 != "=" { next }
  $1 == "(SERVICE_NAME" && $3 ~ s { print a }
  $1 !~ /^(/ { a=$1 }
' s="pri"

Hi,
thanks for the awk --- I do not understand how it should work and I get an error I can not correct:

awk: cmd. line:4: error: Unmatched ( or \(: /^(/

And I'd like to search for a service name that contains 'pri'. Can you please explain?

I played around with sed:

sed -n '/DESCR/{x;p;d;}; x'

returns all lefthand sides of the tnsnames.ora....if only I could add something to match the DESCRIPTION with a service name matching 'pri'

Hi,

thanks again for giving me the time to find out what to correct...I now run

awk '
  $2 != "=" { next }
  $1 == "(SERVICE_NAME" && $3 ~ s { print a }
  $1 !~ /^\(/ { a=$1 }
'  s="pri" tnsnames.ora

...and it matches just fine. How do I make it case insensitive? Can you please explain how it works?

I think the first line skips over the tnsnames.ora until it finds a pattern 'variable ='. So this will give us the left hand side in $1?
The second line searches for the SERVICE_NAME entry, where the value matches s, which is set on the command line to be 'pri'.
You store this in $1 ....but didn't we keep the left hand side there?

... I do not understand the third line at all.

I forgot that ( is special in ERE, that awk uses. You found it: needs to be escaped. An alternative would be [(] .

Each code line is a condition { action } .
All three code lines are run for each input line.
If the condition in the 2nd code line is true it performs the action: print variable a .
This is set in the 3rd code line to field#1, if it does not have a ( at the beginning.