本文简要介绍ruby语言中 Shellwords模块
的用法。
像 UNIX Bourne shell 一样操作字符串
该模块根据 UNIX Bourne shell 的单词解析规则处理字符串。
shellwords() 函数最初是 shellwords.pl 的一个端口,但经过修改以符合 IEEE Std 1003.1-2008, 2016 Edition [1] 的 Shell & Utilities 卷。
用法
您可以使用 Shellwords
将字符串解析为 Bourne shell 友好的 Array
。
require 'shellwords'
argv = Shellwords.split('three blind "mice"')
argv #=> ["three", "blind", "mice"]
一旦你需要 Shellwords
,你可以使用拆分别名 String#shellsplit
。
argv = "see how they run".shellsplit
argv #=> ["see", "how", "they", "run"]
他们将引号视为特殊字符,因此不匹配的引号将导致 ArgumentError
。
argv = "they all ran after the farmer's wife".shellsplit
#=> ArgumentError: Unmatched quote: ...
Shellwords
还提供了相反的方法。 Shellwords.escape
或其别名 String#shellescape
转义字符串中的 shell 元字符以在命令行中使用。
filename = "special's.txt"
system("cat -- #{filename.shellescape}")
# runs "cat -- special\\'s.txt"
注意“-”。如果没有它,如果 cat(1) 以“-”开头,它将把以下参数视为命令行选项。保证 Shellwords.escape
将字符串转换为 Bourne shell 将解析回原始字符串的形式,但程序员有责任确保将任意参数传递给命令不会造成任何损害。
Shellwords
还带有 Array
、 Array#shelljoin
的核心扩展。
dir = "Funny GIFs"
argv = %W[ls -lta -- #{dir}]
system(argv.shelljoin + " | less")
# runs "ls -lta -- Funny\\ GIFs | less"
您可以使用此方法从参数数组构建完整的命令行。
作者
-
和光青山
-
Akinori MUSHA <knu@iDaemons.org>
接触
-
Akinori MUSHA <knu@iDaemons.org>(当前维护者)
资源
相关用法
- Ruby Shellwords.shellsplit用法及代码示例
- Ruby Shellwords.shellescape用法及代码示例
- Ruby Shellwords.shelljoin用法及代码示例
- Ruby Symbol capitalize用法及代码示例
- Ruby SizedQueue clear()用法及代码示例
- Ruby Spotter.spot_op_asgn2_for_name用法及代码示例
- Ruby StringScanner skip_until用法及代码示例
- Ruby StringScanner search_full用法及代码示例
- Ruby String.match?用法及代码示例
- Ruby StringScanner.beginning_of_line?用法及代码示例
- Ruby Stat.stat <=>用法及代码示例
- Ruby Symbol.to_proc用法及代码示例
- Ruby Symbol.end_with?用法及代码示例
- Ruby StringScanner restsize用法及代码示例
- Ruby Spotter.spot_opcall_for_name用法及代码示例
- Ruby Set flatten()用法及代码示例
- Ruby SpecificationProvider.requirement_satisfied_by?用法及代码示例
- Ruby Set.replace用法及代码示例
- Ruby String delete!用法及代码示例
- Ruby String chop!用法及代码示例
- Ruby SizedQueue push()用法及代码示例
- Ruby Specification.file_name用法及代码示例
- Ruby SimpleDelegator.__setobj__用法及代码示例
- Ruby String.unpack用法及代码示例
- Ruby Stat.world_writable?用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Shellwords模块。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。