用linux命令行替换整个段落

rad*_*man 5 c++ linux perl replace sed

我遇到的问题非常简单(或者看起来似乎如此).我想要做的就是用另一个段落替换一段文本(它是标题注释).这需要在目录层次结构(源代码树)中的各种文件中进行.

要替换的段落必须完全匹配,因为存在类似的文本块.

例如

取代

// ----------
// header
// comment
// to be replaced
// ----------
Run Code Online (Sandbox Code Playgroud)

// **********
// some replacement
// text
// that could have any
// format
// **********
Run Code Online (Sandbox Code Playgroud)

我已经看过使用sed,从我可以告诉它可以处理的最多行数是2(使用N命令).

我的问题是:从linux命令行执行此操作的方法是什么?

编辑:

获得的解决方案:最佳解决方案是Ikegami的完全命令行,最适合我想做的事情.

我的最终解决方案需要一些调整; 输入数据包含许多特殊字符,替换数据也是如此.为了解决这个问题,需要对数据进行预处理以插入适当的\n和转义字符.最终产品是一个带有3个参数的shell脚本; 包含要搜索的文本的文件,包含要替换的文本的文件和用于递归解析具有.cc和.h扩展名的文件的文件夹.从这里定制起来相当容易.

脚本:

#!/bin/bash
if [ -z $1 ]; then
    echo 'First parameter is a path to a file that contains the excerpt to be replaced, this must be supplied'
  exit 1
fi

if [ -z $2 ]; then
    echo 'Second parameter is a path to a file contaiing the text to replace with, this must be supplied'
  exit 1
fi

if [ -z $3 ]; then
    echo 'Third parameter is the path to the folder to recursively parse and replace in'
  exit 1
fi

sed 's!\([]()|\*\$\/&[]\)!\\\1!g' $1 > temp.out
sed ':a;N;$!ba;s/\n/\\n/g' temp.out > final.out
searchString=`cat final.out`
sed 's!\([]|\[]\)!\\\1!g' $2 > replace.out
replaceString=`cat replace.out`

find $3 -regex ".*\.\(cc\|h\)" -execdir perl -i -0777pe "s{$searchString}{$replaceString}" {} +
Run Code Online (Sandbox Code Playgroud)

ike*_*ami 8

find -name '*.pm' -exec perl -i~ -0777pe'
    s{// ----------\n// header\n// comment\n// to be replaced\n// ----------\n}
     {// **********\n// some replacement\n// text\n// that could have any\n// format\n// **********\n};
' {} +
Run Code Online (Sandbox Code Playgroud)