更改 2 行之间存在的行

Change a line that exists between 2 lines

我想修改段落中两行之间的一行。 例如我有这个文件包含

fruits
apple
banana
end fruits
----
all list
egg
milk
banana
end list

我想将水果块内的香蕉(在水果和最终水果之间)更改为浆果。 如何操作?

这可能符合您的需要:

awk '
fruits && /banana/ { [=10=] = "berry" }
/fruits/  { fruits = 1 }
/end fruits/ { fruits = 0 }
1
' 

上面的代码有一个很大的假设:如果 "banana" 出现在 "fruits" 和 "end fruits" 之间,则可以更改整行。如果你只想替换"bananas",你可以改变操作如下:

awk '
fruits && /banana/ { gsub( "banana", "berry" ) }
/fruits/  { fruits = 1 }
/end fruits/ { fruits = 0 }
1
'

上面我们将所有 "banana" 替换为 "berry",而不是替换整行 ( $0 )。现在因为我们正在使用 gsub(),我们实际上可以删除“&& /banana/”来产生这个:

awk '
fruits  { gsub( "banana", "berry" ) }   # if in fruits, do sub
/fruits/  { fruits = 1 }                # weve entered the fruits block
/end fruits/ { fruits = 0 }             # weve left the block
1                                       # print each line
'

luciole 建议使用范围。这是程序再次使用范围(并消除水果标志):

awk '
/fruits/,/end fruits/  { gsub( "banana", "berry" ) }
1
'

使用上面的范围,程序看起来很像 Cyrus 的答案。

能否请您尝试以下。

awk '
/^fruits$/{
  found=1
}
found && /banana/{
  [=10=]="your new line here"
  found=""
}
1
'  Input_file

说明:为以上代码添加详细说明。

awk '                         ##Starting awk program from here.
/^fruits$/{                   ##Checking if a line has value fruits in it then do following.
  found=1                     ##Setting value of found to 1 here, kind of FLAG to check either fruits string found in lines till now or not.
}
found && /banana/{            ##Checking condition if string banana found in line and variable found is SET then do following.
  [=11=]="your new line here"     ##Setting current line value to new line value here.
  found=""                    ##Nullifying variable found here.
}
1                             ##Mentioning 1 will print edited/non-edited lines here.
'  Input_file                 ##Mentioning Input_file name here.

使用 sed:

sed '/^fruits$/,/^end fruits$/{ s/banana/berry/ }' file

输出:

fruits
apple
berry
end fruits
----
all list
egg
milk
banana
end list