2013-08-28 48 views
0

首先,感謝這樣一個美好的社區!我一直從這裏在stackoverflow上分享的偉大知識中獲益。在匹配圖案的下方和上方插入文字

來到我面臨的問題:

我有一堆在這些文件我想搜索模式(多線)的文件(約200),如果匹配的模式,我想在模式的上方和下方添加一些文字。

E.g

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下面#endif這是正下方Parent1.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的所以可以使用幫助

非常感謝:-)

最好的問候, 馬克

回答

0

編輯:沒有正確讀請求。 這似乎給正確的O/P在錯誤的位置

awk '/PARENT1_H/ {print "#ifndef NOPARENT" RS $0;f=1} /#endif/ && f {print $0;f=0} !/PARENT1_H/' file 
+0

非常感謝!這非常有幫助。我用這個,對我很好! –

+0

不客氣 – Jotne

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 
+0

#ENDIF,SE O/P請求。 _ #endif下方是#endif,它正下方Parent1.h_ – Jotne

+0

你是對的 - 沒有看到!將更正... – fugu

+0

非常感謝您的解決方案! –

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 
+1

非常感謝!這非常有幫助。我用這個,對我很好。 –

+0

如果您對此感到滿意,請記得單擊答案旁邊的複選標記,以便其他人不會浪費時間嘗試爲您提供替代方案。 –