[英]Replace string with another depending on another line
I need to write a script, that goes through a bunch of text files and replaces a certain string with another.我需要编写一个脚本,它遍历一堆文本文件并用另一个替换某个字符串。 The other one is located two lines below the certain string.
另一个位于特定字符串下方的两行。 Like this:
像这样:
some text
this is the first line (helloWorld).
this is the second line.
This is the third line (patternxxx).
more text
And I want this:我想要这个:
some text
this is the first line (helloxxxWorld).
this is the second line.
This is the third line (patternxxx).
more text
I'm under Linux.我在Linux下。
awk '
BEGIN { mr=3 }
/helloWorld/{ mr=0; gsub("helloWorld","helloxxxWorld");print; };
mr==2 { gsub("pattern", "patternxxx");}
mr++
'
test:测试:
$ 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
You can achieve this using sed, see below command.您可以使用 sed 来实现这一点,请参见下面的命令。 this will permanently make changes in the files.
这将永久更改文件。
sed -i 's/helloWorld/helloxxxWorld/g' file1 file2 ...filen
You can loop files one by one also.您也可以一个一个地循环文件。
for file in `ls`;
do
sed -i 's/helloWorld/helloxxxWorld/g' $file;
echo "$file completed";
done
make sure you have backups for the files.确保您有文件的备份。
This might work for you (GNU sed):这可能对你有用(GNU sed):
sed -ri '1N;N;s/(hello)(World.*\n.*\n.*pattern(xxx))/\1\3\2/;P;D' file1 file2 ...
Open a three line window in the file and pattern match on the first and third lines throughout the file.在文件中打开一个三行窗口,并在整个文件的第一行和第三行进行模式匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.