Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


share|improve this question
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

Your Answer


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.