我需要编写一个脚本,它会遍历一堆文本文件并用另一个字符串替换某个字符串。另一个位于特定字符串下方两行。像这样:
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 :(得分: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
答案 1 :(得分:0)
您可以使用sed实现此目的,请参阅以下命令。这将永久地对文件进行更改。
config.after_initialize do
response = HTTParty.post(the_rest_url,
{
:basic_auth => @auth
})
puts response.message
end
您也可以逐个循环文件。
sed -i 's/helloWorld/helloxxxWorld/g' file1 file2 ...filen
确保您拥有文件的备份。
答案 2 :(得分:0)
这可能适合你(GNU sed):
sed -ri '1N;N;s/(hello)(World.*\n.*\n.*pattern(xxx))/\1\3\2/;P;D' file1 file2 ...
在文件中打开一个三行窗口,并在整个文件的第一行和第三行上匹配模式。