1998-01-16 07:19:09 -05:00
|
|
|
#
|
2003-01-26 05:11:30 -05:00
|
|
|
# shellwords.rb: Split text into an array of tokens a la UNIX shell
|
1998-01-16 07:19:09 -05:00
|
|
|
#
|
|
|
|
|
2003-01-26 05:11:30 -05:00
|
|
|
#
|
|
|
|
# This module is originally a port of shellwords.pl, but modified to
|
|
|
|
# conform to POSIX / SUSv3 (IEEE Std 1003.1-2001).
|
|
|
|
#
|
|
|
|
# Examples:
|
|
|
|
#
|
|
|
|
# require 'shellwords'
|
|
|
|
# words = Shellwords.shellwords(line)
|
|
|
|
#
|
|
|
|
# or
|
|
|
|
#
|
|
|
|
# require 'shellwords'
|
|
|
|
# include Shellwords
|
|
|
|
# words = shellwords(line)
|
|
|
|
#
|
1998-01-16 07:19:09 -05:00
|
|
|
module Shellwords
|
2003-01-26 05:11:30 -05:00
|
|
|
|
|
|
|
#
|
|
|
|
# Split text into an array of tokens in the same way the UNIX Bourne
|
|
|
|
# shell does.
|
|
|
|
#
|
|
|
|
# See the +Shellwords+ module documentation for an example.
|
|
|
|
#
|
1998-01-16 07:19:09 -05:00
|
|
|
def shellwords(line)
|
|
|
|
words = []
|
2005-11-08 18:41:40 -05:00
|
|
|
field = ''
|
2005-11-10 07:05:57 -05:00
|
|
|
line.scan(/\G\s*(?>([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|\z)?/m) do
|
|
|
|
|word, sq, dq, esc, garbage, sep|
|
|
|
|
raise ArgumentError, "Unmatched double quote: #{line.inspect}" if garbage
|
|
|
|
field << (word || sq || (dq || esc).gsub(/\\(?=.)/, ''))
|
2005-11-08 18:41:40 -05:00
|
|
|
if sep
|
|
|
|
words << field
|
|
|
|
field = ''
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
words
|
|
|
|
end
|
2003-01-26 05:11:30 -05:00
|
|
|
|
1998-01-16 07:19:09 -05:00
|
|
|
module_function :shellwords
|
|
|
|
end
|