我拥有的问题非常简单(或者看起来如此)。我想要做的就是用另一段替换一段文本(它是一个标题注释)。这将需要通过目录层次结构(源代码树)中的各种文件进行。从linux命令行中用另一个替换整个段落
由于存在相似的文本块,所以要替换的段落必须完全匹配。
例如
要更换
// ----------
// header
// comment
// to be replaced
// ----------
随着
// **********
// some replacement
// text
// that could have any
// format
// **********
我已经看过用SED,从我可以告诉数量最多的,它可以工作线是2(用N命令)。
我的问题是:如何从linux命令行执行此操作?
编辑:获得
解决方法:最好的解决办法是池上的,全面的命令行和最适合什么,我想做的事。
我的最终解决方案需要一些调整;输入数据与替换数据一样包含许多特殊字符。为了解决这个问题,需要预先处理数据以插入适当的\ n和转义字符。最终产品是一个需要3个参数的shell脚本;包含要搜索的文本的文件,包含要替换的文本的文件以及递归解析扩展名为.cc和.h的文件的文件夹。从这里定制相当容易。
SCRIPT:
#!/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,包括正则表达式中的换行符吗? – wim
我试过了,发现这个:http://backreference.org/2009/12/23/how-to-match-newlines-in-sed/ – radman