下面是我在脚本中的"一行"。
#!/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: /([^])#/
问题
所以问题是让它在ruby -pe ''
中工作的方法是什么?
在单行中使用%q||
而不是单引号,它实际上是相同的,但它不会弄乱命令行单引号:
puts ARGF.read.gsub(RE1) { Regexp.last_match[0].gsub(/([^\])#/,%q|1\#|) }
我不知道你想做什么,但是转义要在 shell 中使用的字符串的标准方法是这样的:
require "shellwords"
`some_command #{Shellwords.escape(some_command_written_in_ruby_string)}`