1

i have about 1000 file with angle brackets include directive. I'd like to change this directive with any kind of script like the example below:

#include <file.h>

to:

#include "file.h"

or

#include <dir/file.h>

to

#inlcude "dir/file.h"

Thanks in advance.

---- EDITING ----- i have tried this script:

for myfile in $(find ./include); do

        sed -i '/^#include/s/<\([^>]*\)>/"\1"/' "${myfile}" > /dev/null
done

but the result is: sed: 1: "./include/DIR/FILE.h": invalid command code .

pasqui86
  • 529
  • 1
  • 7
  • 22

2 Answers2

3
sed '/^#[[:blank:]]*include/s/<\([^>]*\)>/"\1"/' your_input

This only modifies lines that start with #include and in those lines, it replaces < ... > by " ... ", using a backreference (\1) to designate the content inside the brackets.

And if you want to do that on a number of files, just include that in a Bash loop, with the -i option of GNU sed to do the transformation directly into the file:

for myfile in ...
do
  sed -i'' '/^#[[:blank:]]*include/s/<\([^>]*\)>/"\1"/' "${myfile}"
done
jaybee
  • 925
  • 4
  • 11
  • the bash script say: -i may not be used with stdin – pasqui86 Aug 19 '14 at 09:00
  • 1
    Note the OP is on OSX, and `sed -i` does not work there. Hence, it is best to just use a normal `sed '...' file > new_file && mv new_file file`. Or use `sed -i '' '...' file`, or even `sed -i.bak '...' file`. – fedorqui Aug 19 '14 at 09:40
  • 1
    Thanks @fedorqui, I have edited consequently. Personally, I almost never use this `-i` option anyway, it's always better practice to backup when you do large batch alterations... And only delete after you have checked everything is ok (in this case, after compiling the project). – jaybee Aug 19 '14 at 10:32
0

Assuming your files are under the directory directory-name:

grep -rl '#include <.*>' directory-name/ | xargs sed -i 's/#include <\(.*\)>/#include "\1"/g'
Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34