Extracting part of a string

I have a file of the form

server.corp.abc.com:/vol/test/xyz
server2.corp.def.com:/vol/stage/123
server3.corp.xyz.net:/vol/prod/abc

and etc.

How do I return a list of only the server names? In other words
everything up to but not including the “:”. I can read the file in and
can even split it at the “:” but can’t seem to figure out how to only
get server.corp.abc.com
server2.corp.def.com
server3.corp.xyz.net

Any help is appreciated.
Thanks,
Jon

I’m sure somebody will come up with a one-liner (they always do). :wink: But
I would do this:

ruby-1.9.3-p125 :001 > server_names =
%w{server.corp.abc.com:/vol/test/xyz,
server2.corp.def.com:/vol/stage/123, server3.corp.xyz.net:/vol/prod/abc}
=> [“server.corp.abc.com:/vol/test/xyz,”,
server2.corp.def.com:/vol/stage/123,”,
server3.corp.xyz.net:/vol/prod/abc”]
ruby-1.9.3-p125 :002 > server_names.each do | name |
ruby-1.9.3-p125 :003 > servername = name.split(“:”)
ruby-1.9.3-p125 :004?> print “#{servername[0]}\n”
ruby-1.9.3-p125 :005?> end
server.corp.abc.com
server2.corp.def.com
server3.corp.xyz.net
=> [“server.corp.abc.com:/vol/test/xyz,”,
server2.corp.def.com:/vol/stage/123,”,
server3.corp.xyz.net:/vol/prod/abc”]

Wayne

On Tue, Jul 17, 2012 at 3:20 AM, Jon R. [email protected] wrote:

can even split it at the “:” but can’t seem to figure out how to only
get server.corp.abc.com
server2.corp.def.com
server3.corp.xyz.net

I like

$ cat x
server.corp.abc.com:/vol/test/xyz
server2.corp.def.com:/vol/stage/123
server3.corp.xyz.net:/vol/prod/abc

irb(main):001:0> s=File.foreach(“x”).map {|l| l[/^\s*([^:\s]+)/, 1]}
=> [“server.corp.abc.com”, “server2.corp.def.com”,
server3.corp.xyz.net”]

Kind regards

robert

Thanks to everyone. I really liked them all and tried yours Robert and
it worked great!
Jon

Hi,

You can use a regular expression to extract the server names:

text = ‘server.corp.abc.com:/vol/test/xyz
server2.corp.def.com:/vol/stage/123
server3.corp.xyz.net:/vol/prod/abc’

servers = text.scan /^\s*([^:\s]+)/
p servers

This looks for the beginning of a line followed by whitespace followed
by characters, which are neither colons nor whitespace. The latter part
is then saved.

If you don’t like the strings being in subarrays, you can append “map
&:first”.