本文簡要介紹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模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。