2017-07-07 47 views
0

以下是我的腳本中的「單行」。將單行腳本製作爲單行命令的方法?

#!/usr/bin/ruby 

puts ARGF.read.gsub(/\\caption\{((?:[^{}]+|\{\g<1>\})+)\}/m) { |xx, yy| 
    Regexp.last_match[0].gsub(/([^\\])#/,'\1\\#') } 

如果我只是在ruby -pe ''插入我得到

-e:1: syntax error, unexpected $undefined, expecting ')' 
...ast_match[0].gsub(/([^\\])#/,1\#) } 
...        ^

加上雙引號,我得到

-e:1: premature end of char-class: /([^\])#/ 

問題

所以,問題是什麼方法使其在工作?

+0

它包含單引號,所以當你將它嵌入在命令行上單引號,你需要躲避內單引號。或者使用一個備用的引用機制 –

+0

我剛剛嘗試並用錯誤更新了OP。 –

+0

@mudasobwa你是對的,評論已更新。 –

回答

5

使用%q||,而不是在一個班輪單引號,這是實際上是相同的,但它不會亂用命令行單引號:

puts ARGF.read.gsub(RE1) { Regexp.last_match[0].gsub(/([^\\])#/,%q|\1\\#|) } 
0

我不知道你想這樣做,但在shell中使用轉義字符串的標準方式是這樣的:

require "shellwords" 

`some_command #{Shellwords.escape(some_command_written_in_ruby_string)}` 
相關問題