Multi-line delete with sed

I am trying to use sed to remove all occurrences

#ifdef _WIN32

#endif

Where everything that exists between #ifdef and #endif is an empty string. I have limited experience using sed, I read some documentation on multi-line functions, but I can't seem to understand. Any help is appreciated!

+5
source share
3 answers

For this assignment, I would recommend using a tool designed for the assignment, rather than sed.

  • Use coan ; it has a mode for editing lines #ifdefand #ifndefand #ifand #elsif. For example, you should use:

    coan source -U_WIN32 sourcefile.c
    

_WIN32, , .

. : C, #ifdef / undefined?

+4

sed -e '/^#ifdef _WIN32/,/^#endif/d', .

+5

If there are pairs #ifdef _WIN32/#endifthat have non-empty lines between them that you do not want to delete, use the following:

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

Enter

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
+2
source

All Articles