【问题标题】:Inserting Specific function within a Block. Scripting在块中插入特定功能。脚本
【发布时间】:2013-10-03 09:02:53
【问题描述】:

假设您有一个文件 test.cpp,其中包含以下几行

Test(func_class,func1)
{
  Test_Func1();
  Test_Func2();
  Test_Func3();
}

Test(func_class,func3)
{
  Test_Func1();
  Test_Func9();
  Test_Func3();
}

Test(func_class,func2)
{
  Test_Func6();
  Test_Func7();
  Test_Func3();
}

现在我想在大括号之间插入一个新行,例如 Test(func_class,func1/2/3) 插入后会像

Test(func_class,func1)
{
  Test_Func1();
  Test_newFunc6();
  Test_Func2();
  Test_Func3();
}

Test(func_class,func3)
{
  Test_Func1();
  Test_newFunc6();
  Test_Func9();
  Test_Func3();
}

Test(func_class,func2)
{
  Test_Func6();
  Test_newFunc6();
  Test_Func7();
  Test_Func3();
}

这可以使用脚本来完成。任何人都可以请建议shell脚本或perl python来做到这一点,

【问题讨论】:

    标签: python perl shell


    【解决方案1】:

    以下可能会有所帮助。这是python 代码:

    cpp = open("test.cpp","r")
    lines = cpp.readlines()
    printExtraAfterOneLine = False
    for line in lines:
      if printExtraAfterOneLine:
        print line
        print '  Test_newFunc6();'
        printExtraAfterOneLine = False
      else:
        if line.strip() == "{":
          printExtraAfterOneLine = True
        print line
    

    【讨论】:

      【解决方案2】:

      其中gash.txt 是输入文件,out.txt 是输出文件:

      蟒蛇:

      extra = '  Test_newFunc6();\n'
      
      fh  = open('gash.txt')
      out = open('out.txt','w')
      
      for line in fh:
          out.write(line)
          if line.startswith('{'):
              # Read the next line
              buff = fh.readline()
              out.write(buff)
              out.write(extra)
      
      fh.close()
      out.close()
      

      perl:

      use warnings;
      use strict;
      
      my $extra = "  Test_newFunc6();\n";
      
      open(my $fh, '<', 'gash.txt') || die "gash.txt: $!";
      open(my $out, '>', 'out.txt') || die "out.txt: $!";
      
      while (<$fh>) {
          print $out $_;
          if (substr($_, 0, 1) eq '{') {
              # Read the next line
              my $buff = <$fh>;
              print $out $buff;
              print $out $extra;
          }
      }
      
      close($fh);
      close($out);
      

      重击:

      extra="  Test_newFunc6();\n";
      wFlag=false
      
      exec 3> out.txt
      
      IFS=
      while read -r line
      do
          echo "$line" >&3
      
          $wFlag && echo "$extra" >&3
      
          if [[ ${line:0:1} == '{' ]]
          then
              wFlag=true
          else
              wFlag=false
          fi
      done < gash.txt
      
      exec 3<&-
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多