【发布时间】:2011-12-18 11:59:26
【问题描述】:
我遇到的问题非常简单(或者看起来如此)。我要做的就是用另一段替换一段文本(它是标题注释)。这需要在目录层次结构(源代码树)中的不同数量的文件中发生。
要替换的段落必须完整匹配,因为存在类似的文本块。
例如
替换
// ----------
// 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}" {} +
【问题讨论】:
-
你不能只使用 sed,包括正则表达式中的换行符吗?
标签: c++ linux perl replace sed