首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在块中插入特定函数。编写脚本

在块中插入特定函数。编写脚本
EN

Stack Overflow用户
提问于 2013-10-03 17:02:54
回答 2查看 40关注 0票数 1

假设您有一个包含以下行的文件test.cpp

代码语言:javascript
复制
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();
}

现在我想在花括号之间插入一行,例如: in Test(func_class,func1/2/3),插入后将如下所示

代码语言:javascript
复制
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来做这件事,

EN

回答 2

Stack Overflow用户

发布于 2013-10-03 17:17:54

下面的内容可能会有所帮助。这是python代码:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2013-10-03 19:26:53

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

python:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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);

bash:

代码语言:javascript
复制
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<&-
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19155051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档