Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

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 '…' {} +
share|improve this answer
    
Perfect, thanks –  Cookie May 31 '11 at 15:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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