0

まず第一に、私たちが持っている素晴らしいコミュニティに感謝します!! 私は常に、ここで共有されているスタックオーバーフローに関する優れた知識の恩恵を受けてきました。

私が直面していた問題に来て:

たくさんのファイル (約 200) があります。これらのファイルでパターン (複数行) を検索し、パターンが一致する場合は、パターンの上下にテキストを追加したいと考えています。

例えば

File1.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

編集: リクエストを正しく読み取れませんでした。これは正しい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 に答える
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 に答える