简体   繁体   中英

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" .

I've written a one-line perl script as follows:

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?

You have multiple odd slashes in your Perl script. The backrefs should be \\1 , \\2 etc and many of the rest should be dropped entirely.

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| with no slashes at all (the only remaining forward slash is the directory separator between project-head and the original file name).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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