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 .compact
ing 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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With