5

I'm trying to use sed to delete all occurrences of

#ifdef _WIN32

#endif

Where all that exists between #ifdef and #endif is an empty line. I have limited experience using sed, I've read some documentation on the multi line features but I can't seem to figure it out. Any help is appreciated!

lyricat
  • 1,988
  • 2
  • 12
  • 20

3 Answers3

5

You can try sed -e '/^#ifdef _WIN32/,/^#endif/d' but it does not generalize to more complex cases of nesting.

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
  • where i can find the documentation for this /,/ ? – Guilherme Jul 06 '12 at 03:31
  • @Guilherme you can see it in the manual page where it talks about *addresses*. Any two addresses can be joined by a comma to make an inclusive range. E.g. `1,$` for the whole file, or `/hello/,$` for a line containing `hello` until the end of the file, or `1,10` for the first 10 lines. – Ben Jackson Jul 06 '12 at 05:01
4

For this job, I'd recommend using a tool designed for the job - rather than sed.

  • Use coan; it has a mode for editing #ifdef and #ifndef and #if and #elsif lines selectively. For example, you'd use:

    coan source -U_WIN32 sourcefile.c
    

This would deal with all _WIN32 sections, leaving behind only what was necessary.

See also my related question: Is there a C pre-processor which eliminates #ifdef blocks based on values defined/undefined?

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Thanks for contributing this one. I knew such a program existed when I gave the `sed` answer but I didn't find it with quick googling. – Ben Jackson Jan 05 '11 at 22:49
2

If there exists pairs of #ifdef _WIN32/#endif that have non-empty lines between them that you don't want to delete, then use the following:

sed 'N;N;s/\n#ifdef _WIN32\n[[:space:]]*\n#endif\n/\n/;P;D'

Input

this is the first line
#ifdef _WIN32
  // Don't delete this comment!
#endif

stuff here
more stuff here
#ifdef _WIN32

#endif
last line

Output

$ sed 'N;N;s/\n#ifdef _WIN32\n[[:space:]]*\n#endif\n/\n/;P;D' ifdef.sed
this is the first line
#ifdef _WIN32
  // Don't delete this comment!
#endif

stuff here
more stuff here
last line
SiegeX
  • 135,741
  • 24
  • 144
  • 154