我爲一個項目製作了一個簡單的shell,並且我想讓參數字符串像在Bash中一樣被解析。如何在Ruby中分割參數字符串Bash風格?
foo bar "hello world" fooz
應該改爲:
["foo", "bar", "hello world", "fooz"]
等。目前我一直在使用CSV::parse_line
,列分隔符設置爲" "
和.compact
荷蘭國際集團輸出。問題是我現在必須選擇是否要支持單引號或雙引號。 CSV
不支持多個分隔字符。
Python有正是這種所謂的shlex
模塊:
>>> shlex.split("Test 'hello world' foo")
['Test', 'hello world', 'foo']
>>> shlex.split('Test "hello world" foo')
['Test', 'hello world', 'foo']
是否有任何內置隱藏在Ruby中的模塊,可以做到這一點?任何解決方案的建議,將不勝感激。
當然有:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html#method -C-shellsplit。 :) – squiguy