3

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.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Dumbo
  • 1,516
  • 6
  • 16
  • 20

2 Answers2

9

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).
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
RomanPerekhrest
  • 29,703
  • 3
  • 43
  • 67
  • 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
-2

I have done by below command

input.txt

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

command:

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

output

#include "../includes/common.h"
Praveen Kumar BS
  • 5,139
  • 2
  • 9
  • 14