在大文件中搜索和替换多行

时间:2014-02-03 11:11:36

标签: regex perl sed

我想在大文件中搜索和替换(大约900 MB)。我在网上搜索了几个小时。

一般来说,有两种适合的工具,sed和perl sed的多行语法似乎非常复杂,所以我尝试了perl。

我的输入数据如下所示:

K 13
svn:mergeinfo
V 498
/code/branches/TEST_ENVIRONMENT_OBC/Implementation//SpecificComponents/SUV/config/TEST:4670-4976
/code/tags/QR_20131111/Implementation/SpecificComponents/SUV/config/TEST:4669
/code/tags/QR_20131211/Implementation/SpecificComponents/SUV/config/TEST:5138
/code/trunk/Implementation/SpecificComponents/SUV/config/OBC:4669-4949
/code/trunk/Implementation/SpecificComponents/SUV/config/TEST:5137-5273
PROPS-END

我想更改 svn:mergeinfo 块并替换部分路径。
所以我为perl写了一个小的正则表达式。

perl -0pe 's/^svn:mergeinfo\nV (\d+)\n(?:\/code(\/(?:branches|tags|trunk)(?:.|\n)+))+\nPROPS-END/svn:mergeinfo\nV \1\n\2\nPROPS-END/m'

它到目前为止工作,但输出数据中的路径仅在第一次出现时更改。

K 13
svn:mergeinfo
V 498
/branches/TEST_ENVIRONMENT_OBC/Implementation//SpecificComponents/SUV/config/TEST:4670-4976
/code/tags/QR_20131111/Implementation/SpecificComponents/SUV/config/TEST:4669
/code/tags/QR_20131211/Implementation/SpecificComponents/SUV/config/TEST:5138
/code/trunk/Implementation/SpecificComponents/SUV/config/OBC:4669-4949
/code/trunk/Implementation/SpecificComponents/SUV/config/TEST:5137-5273
PROPS-END

我需要更改什么来替换所有出现的路径?

不需要使用perl来解决问题。

4 个答案:

答案 0 :(得分:2)

您可以使用sed

sed -r '/svn:mergeinfo/,/PROPS-END/{s#(/code)(/(branches|tags|trunk))(.*)#\2\4#}' inputfile

这会在匹配模式svn:mergeinfoPROPS-END的行之间执行替换。

输入结果为:

K 13
svn:mergeinfo
V 498
/branches/TEST_ENVIRONMENT_OBC/Implementation//SpecificComponents/SUV/config/TEST:4670-4976
/tags/QR_20131111/Implementation/SpecificComponents/SUV/config/TEST:4669
/tags/QR_20131211/Implementation/SpecificComponents/SUV/config/TEST:5138
/trunk/Implementation/SpecificComponents/SUV/config/OBC:4669-4949
/trunk/Implementation/SpecificComponents/SUV/config/TEST:5137-5273
PROPS-END

答案 1 :(得分:1)

perl -pe '$/ ="PROPS-END"; s!/code(?=/(?:branches|tags|trunk))!!g' file

输出

K 13
svn:mergeinfo
V 498
/branches/TEST_ENVIRONMENT_OBC/Implementation//SpecificComponents/SUV/config/TEST:4670-4976
/tags/QR_20131111/Implementation/SpecificComponents/SUV/config/TEST:4669
/tags/QR_20131211/Implementation/SpecificComponents/SUV/config/TEST:5138
/trunk/Implementation/SpecificComponents/SUV/config/OBC:4669-4949
/trunk/Implementation/SpecificComponents/SUV/config/TEST:5137-5273
PROPS-END

答案 2 :(得分:1)

使用awk

awk '/svn:mergeinfo/,/PROPS-END/{sub(/^\/code/,"")}1' file

答案 3 :(得分:0)

您还需要添加全局标记。尽管目标跨越多条线,但多线仅替换一次然后结束。全局标志使其继续尝试匹配,直到没有更多输入文本。

只需在正则表达式结尾处g之后添加m