Shell / sed Program To Remove All C and C++ Comments From

Write the shell / sed program which remove all the comments from a simple C program stored in your current directory. You can assume that the c source code contains only syntactically correct comments:

+start with // and end with a newline

+starting with / and ending / (can be multiline)

+ nesting of comments is not allowed

Make sure that C source is not changed at all.

How do I use this sed script?

$ ./script.sed < input.c<br style="padding: 0; margin: 0"></br>$ ./script.sed < input.c > output.c<br style="padding: 0; margin: 0"></br>$ for c in *.c; do script.sed < $c > /tmp/zyzcc.c; /bin/cp -f /tmp/zyzcc.c $c; done

Sample sed code to remove all comments from sed

  1. #! /bin/sed-nf
  2. # Remove C and C++ comments, by Brian Hiles(brian_hiles@rocketmail.com)
  3. # Sped up(and bugfixed to some extent)by Paolo Bonzini(bonzini@gnu.org)
  4. # Works its way through the line, copying to hold space the text up to the
  5. # first special character(/,", '). The original version went exactly a
  6. # character at a time, hence the greater speed of this one. But the concept
  7. # and especially the trick of building the line in hold space are entirely
  8. # merit of Brian.
  9. :loop
  10. # This line is sufficient to remove C++ comments!
  11. /^/// s,.*,,
  12. /^$/{
  13. x
  14. p
  15. n
  16. b loop
  17. }
  18. /^"/{
  19. :double
  20. /^$/{
  21. x
  22. p
  23. n
  24. /^"/b break
  25. b double
  26. }
  27. H
  28. x
  29. s,n(.[^"]).,1,
  30. x
  31. s,.[^"]*,,
  32. /^"/bbreak
  33. /^/{
  34. H
  35. x
  36. s,n(.).*,1,
  37. x
  38. s/.//
  39. }
  40. b double
  41. }
  42. /^'/{
  43. :single
  44. /^$/{
  45. x
  46. p
  47. n
  48. /^'/bbreak
  49. b single
  50. }
  51. H
  52. x
  53. s,n(.[^']).,1,
  54. x
  55. s,.[^']*,,
  56. /^'/bbreak
  57. /^/{
  58. H
  59. x
  60. s,n(.).*,1,
  61. x
  62. s/.//
  63. }
  64. b single
  65. }
  66. /^/*/{
  67. s/.//
  68. :ccom
  69. s,^.[^],,
  70. /^$/ n
  71. /^*//{
  72. s/..//
  73. b loop
  74. }
  75. b ccom
  76. }
  77. :break
  78. H
  79. x
  80. s,n(.[^"'/]).,1,
  81. x
  82. s/.[^"'/]*//
  83. b loop

原文链接: https://www.cnblogs.com/MagicLetters/archive/2013/04/14/3444258.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/84546

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午9:37
下一篇 2023年2月9日 下午9:38

相关推荐