Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split up an argument string Bash-style in Ruby?

Tags:

ruby

ruby-2.0

I'm making a simple shell for a project, and I want argument strings to be parsed just like in Bash.

foo bar "hello world" fooz

Should become:

["foo", "bar", "hello world", "fooz"]

Etc. So far I've been using CSV::parse_line, setting the column separator to " " and .compacting the output. The problems is that I must now choose whether I want to support single quotes or double quotes. CSV doesn't support more than a single delimiter character.

Python has a module for exactly this called shlex:

>>> shlex.split("Test 'hello world' foo")
['Test', 'hello world', 'foo']
>>> shlex.split('Test "hello world" foo')
['Test', 'hello world', 'foo']

Are there any hidden built in Ruby modules that can do this? Any suggestions for a solution would be appreciated.

like image 412
Hubro Avatar asked Jun 26 '13 07:06

Hubro


1 Answers

Ruby has the module Shellwords:

require "shellwords"

Shellwords.shellsplit('Test "hello world" foo')
# => ["Test", "hello world", "foo"]

'Test "hello world" foo'.shellsplit
# => ["Test", "hello world", "foo"]
like image 62
toro2k Avatar answered Sep 27 '22 22:09

toro2k