Sed – Replace Backslashes with Forward Slashes Within Double Quotes

grepregular expressionreplacesedsource code

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.

Best Answer

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).
Related Question