Re: String to array as command line



On Mon, 27 Mar 2006, Daniel Harple wrote:


On Mar 26, 2006, at 6:03 PM, lubomir.markovic@xxxxxxxxx wrote:

Hello,

I can't find a function that takes a string as an input, parses it and
returns an array in the exactly same way as command line is parsed into
ARGV array variable.
Could you give me a hint?

Thanks in advance
Lubos

require 'shellwords'
args = Shellwords.shellwords('foo\ bar "another shellword"') # => ["foo bar", "another shellword"]

-- Daniel

but that will only be similar to sh-like shells. i think a portable way to do
it would be

harp:~ > cat a.rb
def command_line string
Marshal::load(IO::popen("ruby -r yaml -e' print Marshal::dump(ARGV) ' #{ string }"){|io| io.read})
end

p command_line(' foo bar foobar ')
p command_line(' "foo bar" "foobar" ')
p command_line(' foo $bar ')
p command_line(' foo "$bar" ')
p command_line(" foo '$bar' ")


harp:~ > ruby a.rb
["foo", "bar", "foobar"]
["foo bar", "foobar"]
["foo"]
["foo", ""]
["foo", "$bar"]

this may be overkill but it should work regardless of the shell in use.

-a
--
share your knowledge. it's a way to achieve immortality.
- h.h. the 14th dali lama


.



Relevant Pages