Hi all,
I have a file (tnsnames.ora in Oracle) from which i have to extract the values of two fields. Suppose following is the content of my file called "inputfile.txt"

(ADDRESS = ( PROTOCOL = TCP ) ( HOST = 1.1 ) ( PORT = 1521 ))
(ADDRESS=(PROTOCOL=TCP)(HOST=2.1)(PORT=1521))
(ADDRESS = ( PROTOCOL = TCP ) ( HOST = 3.1 ) ( PORT = 1521 ))

I want to extract the value of HOST from this file and assin it to an array. For eg. from the above file, i need to get the HOST values and store in the array like

ip[1]=1.1
ip[2]=2.1
ip[3]=3.1

That is i want to extract just the values of HOST from all the lines in the file given. Remember the format is the same but there are spaces in the first and third row but not in the second row. Any help would be greatly appreciated.

Thank you,
Harris.

$ cat file
(ADDRESS = ( PROTOCOL = TCP ) ( HOST = 1.1 ) ( PORT = 1521 ))
(ADDRESS=(PROTOCOL=TCP)(HOST=2.1)(PORT=1521))
(ADDRESS = ( PROTOCOL = TCP ) ( HOST = 3.1 ) ( PORT = 1521 ))
$ awk '{x[++c]=$5}END{for(i=1;i<=c;i++)print "ip["i"]="x[i]}' FS="[=)] *" file 
ip[1]=1.1 
ip[2]=2.1
ip[3]=3.1

Use nawk on Solaris.

And an example using sed and shell. It can be put on one line also, but I broke it up for readability:

sed -e 's/.*HOST *= *//' -e 's/ *).*//' inputfile.txt | (
typeset -i i; i=1
while read a; do
echo "ip[$i]=$a"
i=i+1
done
)

Because a 'freak' wrote bc(1) in sed some years back, I'm sure the whole thing could be done in sed.

A shorter alternative using cat and sed:
cat -n a.a | sed -e 's/^ *\([0-9]*\)\t/ip\[\1\]=/' -e 's/[^]]*HOST *= */=/' -e 's/ *).*//'

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.