简体   繁体   中英

Escaping characters in Ruby Shell

I have a bash command:

git log --numstat --pretty="%H" -1 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}'

I want to assign this command as a string variable and process the output using exec(stringname) method.

The string command breaks at "+%d, -%d\\n" . Is there a way I can escape these special characters?

If you need to quote something that has quotes in it already, use the %q method:

command = %q[git log --numstat --pretty="%H" -1 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}']

Doing all of this in Ruby gives you a lot more control:

require 'open3'

Open3.popen3('git', 'log', '--numstat', '--pretty="%H"', '-1') do |stdin, stdout, stderr, wait_thr|
  stdout.each_line do |line|
    if (line.match(/\A(\d+)\s+(\d+)\s+(.*)/))
      puts '+%d, -%d' % [ $1, $2 ]
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM