tags:

views:

44

answers:

1

I'm new to shell scripting, right now using csh and let's say I have a line in my configuration file like this:

127.0.0.1:2222 127.0.0.2:3333 127.0.0.3:4444

All I want is to parse it for two variables in array :

2222 3333 4444

And another one

127.0.0.1 127.0.0.2 127.0.0.3
+1  A: 

Read 'C Shell Programming Considered Harmful'.

How do you get the right line in the configuration file? I'm about to assume there's just the one line in the file, but as long as you can identify the line, there are ways to do it.

set var1=`sed 's/[0-9.]*:\([0-9]*\)/\1/g' config.file`
set var2=`sed 's/\([0-9.]*\):[0-9]*/\1/g' config.file`

The first captures the 'port numbers' after the dotted-decimal addresses. The second captures the addresses. In each case, the result is assigned to a string with spaces separating the values.


Some more manual bashing (on MacOS X 10.5.8 - 'man csh' prints the 'tcsh' page) suggests you might be after:

set arr1=(`sed 's/[0-9.]*:\([0-9]*\)/\1/g' config.file`)
set arr2=(`sed 's/\([0-9.]*\):[0-9]*/\1/g' config.file`)

With this notation (the parentheses around the back-quoted sed command), you create arrays, and can use:

echo $arr1[1]
echo $arr1[2]
echo $arr1[3]
echo $arr2[1]
echo $arr2[2]
echo $arr2[3]

(assuming the sample data). The part of the manual page where this is noted marks the syntax with '(+)' which might well mean 'extension to standard C shell', so whether this works for you may depend on your environment.

Jonathan Leffler
Thanks mate, this worked out :)
Ebbcom

related questions