2015-10-22 139 views
-1

我需要編寫一個腳本,該腳本通過一堆文本文件並將某個字符串替換爲另一個字符串。另一個位於特定字符串下方兩行。就像這樣:根據另一行替換另一個字符串

some text 
this is the first line (helloWorld). 
this is the second line. 
This is the third line (patternxxx). 
more text 

而且我想這樣的:

some text 
this is the first line (helloxxxWorld). 
this is the second line. 
This is the third line (patternxxx). 
more text 

我在Linux下。

+0

spenibus,thx編輯 – prologic

+0

到目前爲止你嘗試了什麼?用'sed'或者在一個shell要求中做這件事情? –

+0

任何解決方案都可以接受:)我只是給sed添加了標籤,因爲我認爲這將是一個解決方案。 – prologic

回答

0
awk ' 
    BEGIN { mr=3 } 
    /helloWorld/{ mr=0; gsub("helloWorld","helloxxxWorld");print; }; 
    mr==2 { gsub("pattern", "patternxxx");} 
    mr++ 
' 

測試:

$ cat file 
some text 
this is the first line (helloWorld). 
this is the second line. 
This is the third line (pattern). 
more text 
some text 
this is the first line (helloWorld). 
this is the second line. 
this is the second line. 
This is the third line (pattern). 
more text 

$ awk ' 
    BEGIN { mr=3 } 
    /helloWorld/{ mr=0; gsub("helloWorld","helloxxxWorld");print; }; 
    mr==2 { gsub("pattern", "patternxxx");} 
    mr++ 
' file 
some text 
this is the first line (helloxxxWorld). 
this is the second line. 
This is the third line (patternxxx). 
more text 
some text 
this is the first line (helloxxxWorld). 
this is the second line. 
this is the second line. 
This is the third line (pattern). 
more text 
0

你可以做到這一點使用SED,請參見下面的命令。這將永久地在文件中進行更改。

sed -i 's/helloWorld/helloxxxWorld/g' file1 file2 ...filen 

您也可以逐個循環文件​​。

for file in `ls`; 
do 
sed -i 's/helloWorld/helloxxxWorld/g' $file; 
echo "$file completed"; 
done 

請確保您有備份的文件。

0

這可能爲你工作(GNU SED):

sed -ri '1N;N;s/(hello)(World.*\n.*\n.*pattern(xxx))/\1\3\2/;P;D' file1 file2 ... 

公開賽在整個文件中的第一行和第三行的文件和模式匹配三個行窗口。

相關問題