我想给一个服务名称,并获取端口号作为返回。
我的 tnsnames.ora 文件如下所示:
DELUCA =
(DESCRIPTION =
(ADDRESS = (COMMUNITY = TCP.world)(PROTOCOL = TCP)(Host = database.example.com.au)(Port = 32001))
(CONNECT_DATA =
(SID = D10)
)
)
TOTAL =
(DESCRIPTION =
(ADDRESS = (COMMUNITY = TCP.world)(PROTOCOL = TCP)(Host = database.example.com.au)(Port = 32002))
(CONNECT_DATA =
(SID = D11)
)
)
FMAX =
(DESCRIPTION =
(ADDRESS = (COMMUNITY = TCP.world)(PROTOCOL = TCP)(Host = database.example.com.au)(Port = 32003))
(CONNECT_DATA =
(SID = D12)
)
)
答案1
我从未见过 的正式描述tnsnames.ora
,所以我猜测其格式。这是我对脚本的尝试,可以做你想做的事情:
#!/bin/bash
HOST=$1
tr '()' '\n\n' < input |
awk 'BEGIN {host=""; port=""}
/[Hh][Oo][Ss][Tt]/ {host=$3}
/[Pp][Oo][Rr][Tt]/ {port=$3}
host && port {
if (host == "'$HOST'") {print host, port}
host=""; port=""
}
'
awk
这是相当最新的 Arch Linux 安装中的GNU 。
答案2
使用grep
支持 PCRE 的版本(例如 GNU grep
)来列出所有匹配项:
hostname="database.example.com.au"
< inputfile grep -Po "$hostname\)\(Port = \K[0-9]+"
仅列出第一个匹配项:
hostname="database.example.com.au"
< inputfile grep -Po -m1 "$hostname\)\(Port = \K[0-9]+"
使用sed
, 列出所有匹配项:
< inputfile sed -n "s/.*$hostname)(Port = \([0-9][0-9]*\).*/\1/p"
仅列出第一个匹配项:
< inputfile sed -n "0,/$hostname/{s/.*$hostname)(Port = \([0-9][0-9]*\).*/\1/p}"