gpt4 book ai didi

linux - 根据另一行将字符串替换为另一个字符串

转载 作者:太空宇宙 更新时间:2023-11-04 05:25:15 25 4
gpt4 key购买 nike

我需要编写一个脚本,它会遍历一堆文本文件并将某个字符串替换为另一个字符串。另一个位于特定字符串下方两行。像这样:

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下。

最佳答案

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

关于linux - 根据另一行将字符串替换为另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com