I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash s
#!/bin/sed -f
1,/^#include/ {
/^#include/i\
#include "newfile.h"
}
How this script works: For lines between 1 and the first #include
(after line 1), if the line starts with #include
, then prepend the specified line.
However, if the first #include
is in line 1, then both line 1 and the next subsequent #include
will have the line prepended. If you are using GNU sed
, it has an extension where 0,/^#include/
(instead of 1,
) will do the right thing.