0

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
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ebbcom
  • 1
  • The first line is in a config file.
    The second two lines are in shell variables:
    a[0]=2222, a[1]=3333, a[2]=4444
    b[0]=127.0.0.1, b[1]=127.0.0.2, b[2]=127.0.0.3
    is that it? is the more? what do you want to do with these parts?
    – Don Nov 22 '09 at 02:19
  • @Ebbcom: you earn yourself a couple of points when you accept an answer, as well as making those who give you acceptable answers happy. – Jonathan Leffler Nov 22 '09 at 18:14

1 Answers1

2

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
  • 730,956
  • 141
  • 904
  • 1,278