用它替换红宝石一个衬垫;结束块

时间:2016-01-22 15:36:54

标签: ruby regex awk gsub

我想知道如何在我的所有rspec文件代码中替换:

describe ApiController do
  context 'article list exist' do
      #...
      it { should respond_with :success }

      it { should render_template 'refresh_article_in_article_list' }
  end
end

describe ApiController do
  context 'article list exist' do
     #...
     it do
         should respond_with :success

         should render_template 'refresh_article_in_article_list'
     end
  end
end

我能够用vim宏替换一个,但多行不能成功。

this post的帮助下,我试图在ruby gsub中执行此操作,但我失败了,我会继续搜索:

"it { should respond_with :success }\n\nit { should render_template 'refresh_article' }".gsub(/(?<value>{.*})|(it {)|( })/, 'it do \k<value>\nend'))
=> "it do \\nend should respond_with :successit do \\nend\n\nit do \\nend should render_template 'refresh_article'it do \\nend"

1 个答案:

答案 0 :(得分:4)

$ cat tst.awk
NF {
    prevSpaces = spaces
    spaces = $0
    sub(/[^[:space:]].*/,"",spaces)
}
!inBlock && /it *{.*}/ {
    print spaces "it do"
    inBlock = 1
}
inBlock {
    if ( !NF ) {
        print
    }
    else if ( gsub(/.*it *{ *| *} */,"") ) {
        print spaces "    " $0
    }
    else {
        print prevSpaces "end"
        inBlock = 0
    }
}
!inBlock
$
$ awk -f tst.awk file
describe ApiController do
  context 'article list exist' do
      #...
      it do
          should respond_with :success

          should render_template 'refresh_article_in_article_list'
      end
  end
end

不确定它的作用?添加一些“打印”以查看字段和/或变量的设置,并阅读Arnold Robbins的书“Effective Awk Programming”,第4版,如果您有任何问题,请发布具体问题。