本文介绍了用sed或awk替换文本块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是文件的摘录:

COMMAND : /* some text 1 */
ACTION : /* some text 1 in multiple lines */
COMMAND : /* some text 2 */
ACTION : /* some text 2 in multiple lines */
.
.
.

这继续.我想使用sed或awk工具用另一个文本替换从COMMAND开始的文本,直到其对应的ACTION(即下一个COMMAND之前的文本).

This goes on.I would like to replace text starting from a COMMAND till its corresponding ACTION (i.e. before the next COMMAND) with another text using sed or awk tool.

因此,如果我想删除第一个带有某些文本的COMMAND-ACTION组,将得到以下结果.

So if I want to delete the first COMMAND-ACTION group with some text, the following will be the result.

USED SED/AWK HERE
COMMAND : /* some text 2 */
ACTION : /* some text 2 in multiple lines */
.
.
.

推荐答案

已批准:

sed '/COMMAND/,/ACTION/ {
/COMMAND/ i\
Put your new text \
and lines here
d
}' YourFile

使用awk(实际上是nawk或gawk,awk毫无用处),您可以执行以下操作:

With awk (nawk or gawk really, awk is useless) you can do:

replace='myReplaceBlockLine1\nmyReplaceBlockLine2'
nawk '/COMMAND/,/ACTION/{ myvar=replace; gsub(/\\n/,"\n",myvar); print myvar; next} 1'
 "replace=$replace" input_file.txt

两者兼具的缺点-不支持反向引用.使用awk的好处-您可以添加一些逻辑,例如仅替换首次出现或删除重复项

Downside with both - no backreference support.Upside with awk - you can add some logic, like replacing only first occurence or removing duplicates

这篇关于用sed或awk替换文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:30