sed 如何在现有缩进后添加文本?

sed 如何在现有缩进后添加文本?

我有一个 sed 脚本,其中包含:

sed -i '/ *it.*do/! {
          /\.should/ {
            s/\.should/)\.to/
            s/\(\S\)/expect(\1/ 
            # ...others

最后一个s添加expect(到行的开头。我不明白它是如何工作的。

它适用于:

原来的:

  it "uses the given count if set" do
    call('5').should == 5
  end

  it "uses the processor count from Parallel" do
    call(nil).should == 20
  end

后:

  it "uses the given count if set" do
    expect(call('5')).to eq 5
  end

  it "uses the processor count from Parallel" do
    expect(call(nil)).to eq 20
  end

但它没有添加expect(for:

原来的:

  it "does not wait if not run in parallel" do
    ParallelTests.should_not_receive(:sleep)
    ParallelTests.wait_for_other_processes_to_finish
  end

  it "stops if only itself is running" do
    ENV["TEST_ENV_NUMBER"] = "2"
    ParallelTests.should_not_receive(:sleep)
    with_running_processes(1) do
        ParallelTests.wait_for_other_processes_to_finish
      end
  end

之后——不expect(...

  it "does not wait if not run in parallel" do
    ParallelTests).to_not receive(:sleep)
    ParallelTests.wait_for_other_processes_to_finish
  end

  it "stops if only itself is running" do
    ENV["TEST_ENV_NUMBER"] = "2"
    ParallelTests).to_not receive(:sleep)
    with_running_processes(1) do
        ParallelTests.wait_for_other_processes_to_finish
      end
  end

然而它工作时间:
之后:

  it "should be true when there is a Gemfile" do
    use_temporary_directory_for do
      FileUtils.touch("Gemfile")
      expect(ParallelTests.send(:bundler_enabled?)).to eq true
    end
  end

答案1

它只是一个字符类,因为您没有-r设置标志\(\)创建一个组供以后参考,并且\S只是 的互补组\s,因为\s与任何空白匹配的组\S是与除空白之外的任何内容匹配的组。

这意味着正则表达式s/\(\S\)/expect(\1/添加expect(在第一个非空白前面:

# echo ' ' | sed "s/\(\S\)/expect(\1/"

# echo '   a' | sed "s/\(\S\)/expect(\1/"
   expect(a

所以,我想我是想说你的脚本确实改变了这一行:

ParallelTests.should_not_receive(:sleep)

它必须改变它:

# echo "ParallelTests.should_not_receive(:sleep)" | sed '/ *it.*do/! {
    /\.should/ {
        s/\.should/)\.to/
        s/\(\S\)/expect(\1/ 
    }
}'
expect(ParallelTests).to_not_receive(:sleep)

相关内容