I have some C source code which was originally developed on Windows. Now I want to work on it in Linux. There are tons of include directives that should be changed to Linux format, e.g:

#include "..\includes\common.h"

I am looking for a command-line to go through all .h and .c files, find the include directives and replace any backslash with a forward slash.


find + GNU sed solution:

find . -type f -name "*.[ch]" -exec sed -i '/^#include / s|\\|/|g' {} +
  • "*.[ch]" - wildcard to find files with extension .c or .h
  • -i: GNU sed extension to edit the files in-place without backup. FreeBSD/macOS sed have a similar extension where the syntax is -i '' instead.
  • /^#include / - on encountering/matching line which starts with pattern: #include
  • s|\\|/|g - substitute all backslashes \ with forward slashes / (\ escaped with backslash \ for literal representation).
  • You might want to change your qualification regex to /^#\s*include\W/, because you can have whitespace after the #, and the whitespace (which can include tabs) after include is optional (e.g., # include"..\includes\common.h" is legal).  Also, I just did a quick test, and, to my surprise, whitespace before the # was also allowed — I don’t know whether that’s standard.  If it is, then /^\s*#\s*include\W/. – Scott Jan 29 '18 at 21:31

I have done by below command


#include "..\includes\common.h"


 sed 's/\\/\//g' input.txt


#include "../includes/common.h"
  • 1
    Kindly let me know why down voted for my answer – Praveen Kumar BS Jan 28 '18 at 14:33
  • 1
    There are no matching conditions in your command...it will replace any instance it faces. – Saeid Yazdani Jan 29 '18 at 10:23

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.