0

首先,感谢我们拥有如此美好的社区!!我一直受益于在 stackoverflow 上分享的丰富知识。

谈到我面临的问题:

我有一堆文件(大约 200 个) 在这些文件中我想搜索一个模式(多行),如果模式匹配,我想在模式的上方和下方添加一些文本。

例如

文件1.cpp

#ifndef FILE1_H
#define FILE1_H

#ifndef PARENT1_H
#include "Parent1.h"
#endif

#ifndef SIBLING_H
#include "Sibling.h"
#endif

#ifndef PARENT2_H
#include "Parent2.h"
#endif

class File1
{
};

#endif    

在这个文件中,我想在下面添加#ifndef NOPARENT上面#ifndef PARENT1_H#endif下面。#endifParent1.h

我想做同样的事情#ifndef PARENT2_H

所以输出将如下所示:

#ifndef FILE1_H
#define FILE1_H

#ifndef NOPARENT
#ifndef PARENT1_H
#include "Parent1.h"
#endif
#endif


#ifndef SIBLING_H
#include "Sibling.h"
#endif

#ifndef NOPARENT
#ifndef PARENT2_H
#include "Parent2.h"
#endif
#endif

class File1
{
};

#endif    

我有一个这样的匹配列表。例如,我在这里搜索 PARENT1_H、PARENT2_H 等,但我有更多类似 GRANDPARENT1_H、GREATGRANDPARENT_H 等

所以本质上,我想的方法是在这些文件中搜索输入符号(PARENT1_H等),如果找到匹配项,则在#ifndef NOPARENT上方和#endif下方添加文本()。

输入符号很多,要替换的文件也很多。

谁能帮我编写一个使用 sed/awk/perl 执行此操作的脚本。或者任何其他语言/脚本(bash 等)也很棒!

我是 sed/awk/perl 的新手,所以可以使用帮助

非常感谢 :-)

最好的问候,马克

4

3 回答 3

1
$ awk '/#ifndef (PARENT1_H|PARENT2_H)$/{print "#ifndef NOPARENT"; f=1} {print} f&&/#endif/{print; f=0}' file
#ifndef FILE1_H
#define FILE1_H

#ifndef NOPARENT
#ifndef PARENT1_H
#include "Parent1.h"
#endif
#endif

#ifndef SIBLING_H
#include "Sibling.h"
#endif

#ifndef NOPARENT
#ifndef PARENT2_H
#include "Parent2.h"
#endif
#endif

class File1
{
};

#endif
于 2013-08-28T11:35:02.180 回答
0

使用正则表达式怎么样?如果这不是您想要的,请告诉我,我会修改!

#!/usr/bin/perl -w
use strict;

my $file = 'file1.txt';
open my $input, '<', $file or die "Can't read $file: $!";

my $outfile = 'output.txt';
open my $output, '>', $outfile or die "Can't write to $outfile: $!";

while(<$input>){
    chomp;
my (@match) = ($_ =~ /\.*?(\s+PARENT\d+_H)/); # edit - only matches 'PARENT' not 'GRANDPARENT'
    if (@match){
        print $output "#ifndef NOPARENT\n";
        print $output "$_\n";
        print $output "#endif\n";
    }
    else {print $output "$_\n"}
}

输出:

#ifndef FILE1_H
#define FILE1_H

#ifndef NOPARENT
#ifndef PARENT1_H
#endif
#include "Parent1.h"
#endif

#ifndef SIBLING_H
#include "Sibling.h"
#endif

#ifndef NOPARENT
#ifndef PARENT2_H
#endif
#include "Parent2.h"
#endif
于 2013-08-28T10:13:45.737 回答
0

编辑:没有正确阅读请求。这似乎给出了正确的 O/P

awk '/PARENT1_H/ {print "#ifndef NOPARENT" RS $0;f=1} /#endif/ && f {print $0;f=0} !/PARENT1_H/' file
于 2013-08-28T11:04:40.223 回答