当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Shellwords模块用法及代码示例


本文简要介绍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>(当前维护者)

资源

1: IEEE Std 1003.1-2008, 2016 版,Shell & Utilities 卷

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Shellwords模块。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。