2013-06-26 24 views
5

Sto creando una semplice shell per un progetto e voglio analizzare le stringhe degli argomenti proprio come in Bash.Come dividere una stringa argomento in stile Bash in Ruby?

foo bar "hello world" fooz 

dovrebbe diventare:

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

Etc. Finora ho usato CSV::parse_line, impostare il separatore di colonna per " " e .compact ing l'uscita. Il problema è che ora devo scegliere se voglio supportare citazioni singole o doppie virgolette. CSV non supporta più di un singolo carattere di delimitazione.

Python ha un modulo proprio per questo chiamato shlex:

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

ci sono eventuali nascosta costruito in moduli di Ruby che possono fare questo? Qualsiasi suggerimento per una soluzione sarebbe apprezzato.

+1

naturalmente c'è: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html#method -c-shellsplit. :) – squiguy

risposta

8

Ruby ha il modulo Shellwords:

require "shellwords" 

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

'Test "hello world" foo'.shellsplit 
# => ["Test", "hello world", "foo"] 
+0

Credo che sia 'shellsplit', mi hai battuto! – squiguy

+0

@squiguy 'Shellwords # split' è un alias per' Shellwords # shellsplit'. – toro2k

+2

Dopo aver importato "shellwords" puoi anche fare "test" hello world "foo'.shellsplit' – Hubro

Problemi correlati