从另一个关键字搜索点开始搜索并替换匹配第一个关键字实例的行

时间:2013-06-27 12:53:50

标签: shell awk

我有一个通过shell脚本修改的文本文件。

我需要做以下事情:

  1. 从用户那里获取新文本的输入。
  2. 在文件中搜索关键字#1。
  3. 从2.开始,搜索关键字#2。
  4. 用用户提供的输入替换该行(包含关键字#2)。
  5. 例如,我的文件包含以下文字:

    (some text)  
    (some text)  
    (text1_to_search)  
    (some text)  
    (text2_to_search) <- **This needs to be replaced only**  
    (text2_to_search)    
    (some text)
    

    我只需要替换该特定行,并保持文件内容的其余部分不受影响。

2 个答案:

答案 0 :(得分:2)

这是一种方式

awk '/text1_to_search/,/text2_to_search/ && !found{
if($0 ~ /text1_to_search/){found=0};
if($0 ~ /text2_to_search/){print "replacement";found=1;next}};
{print}'

对于两个不重叠的搜索/替换

awk '/text1_to_search/,/text2_to_search/ && !found{if($0 ~ /text1_to_search/){found=0};if($0 ~ /text2_to_search/){print "replacement";found=1;next}};
/Search_String2/,/Search_String3/ && !found2{if($0 ~ /SearchString2/){found2=0};if($0 ~ /Search_String3/){print "replacement2";found2=1;next}};
{print}' 

答案 1 :(得分:0)

awk 'done{print;next}found&&/text2/{while(getline<"replacement")print;done=1;next}/text1/{found=1}1'

假设您有一个名为“replacement”的文件替换。 以下两个通过正则表达式替换:

sed '/text1/,/text2/s/text2/foo/' test.in

如果他们在同一条线上,这将取代那一个和下一个。以下内容仅会改变后者。

awk 'found&&!done&&/text2/{done=sub(/text2/,"foo")}/text1/{found=1}1' test.in
相关问题