3

I am porting a Visual Studio C++ project to Linux, and would like to find all lines in all .h and .cpp files that start with #include and in any of those lines would like to replace the backslash with the forward slash.

There are a few scripts on how to do a search and replace online (using perl or sed for example), but none with a condition.

What's the best way?

Thanks

3

In sed, you can put a regexp (between /…/) before the s command to only perform the replacement on lines containing that regexp. The -i option to modify files in place is specific to GNU sed (which is what you have on Linux and Cygwin).

sed -i -e '/^ *# *include/ s!\\\\!/!g' **/*.h **/*.cpp

In Perl, just put a conditional before doing the replacement.

perl -i -pe 'if (/^\s*#\s*include/) {s!\\\\!/!g}' **/*.h **/*.cpp
perl -i -pe '/^\s*#\s*include/ and s!\\\\!/!g' **/*.h **/*.cpp

The **/ syntax to match files in the current directory and its subdirectories recursively requires zsh, or bash ≥4 after doing shopt -s globstar. With other shells, you need to use find.

find \( -name '*.h' -o -name '*.cpp' \) -exec perl -i -pe '…' {} +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.