简体   繁体   English

Perl一线式操作include目录

[英]Perl one-liner to manipulate include directory

I have several hundred files with include directives that need to be changed. 我有数百个文件,其中包含指令需要更改。

The prototype is #include "MyFile.hpp" , but I need to append a directory in front of every include file like this: #include "project-head/MyFile.hpp" . 原型是#include "MyFile.hpp" ,但是我需要在每个包含文件的前面附加一个目录,如下所示: #include "project-head/MyFile.hpp"

I've written a one-line perl script as follows: 我编写了一个单行的perl脚本,如下所示:

perl -p -i -e 's|/(#include /")/(.*/.hpp)|/1project-head/2|g' test_file.hpp

But the test file doesn't seem to be changing. 但是测试文件似乎没有改变。 What is wrong with my with my perl expression? 我的perl表达式有什么问题?

You have multiple odd slashes in your Perl script. 您的Perl脚本中有多个奇斜杠。 The backrefs should be \\1 , \\2 etc and many of the rest should be dropped entirely. 后向引用应为\\1\\2等,其余的应完全删除。

perl -p -i -e 's|(#include ")(.*\.hpp)|\1project-head/\2|g' test_file.hpp

In case it's not blindingly obvious, / and \\ are two different characters with radically different semantics. 如果不是很明显, /\\是两个具有完全不同语义的不同字符。

The prototype for the substitution command is s/from/to/ but you can use, and have in your code used, different delimiters, so it's s|from|to| 替换命令的原型为s/from/to/但是您可以使用并且在您的代码中使用不同的定界符,因此它是s|from|to| with no slashes at all (the only remaining forward slash is the directory separator between project-head and the original file name). 根本没有斜杠(唯一剩余的正斜杠是project-head和原始文件名之间的目录分隔符)。

The backslash is commonly used as an escape character; 反斜杠通常用作转义符。 for example, \\. 例如\\. matches a literal period (whereas an unescaped . is a regex metacharacter which matches any character except newline). 匹配文字周期(而未转义的.是匹配除换行符以外的任何字符的正则表达式元字符)。 It also has a special meaning in \\1 to refer back to the text matched by the first parenthesized subexpression (though in the replacement part $1 is preferred). 它在\\1也具有特殊含义,以引用由第一个括号括起来的子表达式匹配的文本(尽管在替换部分$1是首选)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM