我遇到的问题非常简单(或者看起来如此)。我想要做的就是用另一段替换一段文本(它是标题注释)。这将需要在目录层次结构(源代码树)中的不同数量的文件中发生。
要替换的段落必须完整匹配,因为存在类似的文本 block 。
例如
替换
// ----------
// header
// comment
// to be replaced
// ----------
与
// **********
// some replacement
// text
// that could have any
// format
// **********
我看过 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}" {} +
最佳答案
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};
' {} +
关于c++ - 从 linux 命令行用另一个替换整个段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7950031/