sed 用 C++ 注释替换(单行)C 注释 [英] sed replace (single-line) C comments with C++ comments

查看:46
本文介绍了sed 用 C++ 注释替换(单行)C 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 sed 将源文件中的所有 C 样式注释替换为 C++ 样式.

How can i use sed to replace all my C-style comments in a source file to C++ style.

所有这些:

int main() {
  /* some comments */
  ...

到:

int main() {
  // some comments
  ...

所有注释都是单行的,中间没有这样的代码:

All comments are single line and there are none in between code like this:

int f(int x /*x-coordinate*/ );

所以我试过这个:

 sed -i 's/ \/\* .*  \*\ / \/\/* /g' src.c

但它使文件保持不变.这篇帖子很相似,但我想了解sed 的表达式语法.自从 "."匹配任何字符并且*"匹配零个或多个某个模式.我假设.*"匹配任意数量的任意字符.

but it leaves the file unchanged. This post is similar, but I'm trying to understand sed's expression syntax. Since "." matches any character and " * " matches zero or more of some pattern. I assume ".*" matches any number of any character.

推荐答案

sed -i 's:\(.*\)/[*]\(.*\)[*]/:\1 // \2:' FILE

这将像这样转换每一行:

this will transform each line like this :

aaa  /* test */

变成这样的一行:

aaa  // test

如果你在同一行有更多的注释,你可以应用这个更复杂的解析器,它会转换如下一行:

If you have more comments on the same line, you can apply this more sophisticated parser, that converts a line like:

aaa /* c1 */ bbb /* c2 */ ccc

进入

aaa  bbb ccc // c1 c2

<小时>

sed -i ':r s:\(.*\)/[*]\(.*\)[*]/\(.*\):\1\3 //\2:;tr;s://\(.*\)//\(.*\)://\2\1:;tr' FILE

更复杂的情况是,当您在一行的字符串中添加注释时,例如 call("/*string*/").这里有一个脚本 c-comments.sed 来解决这个问题:

A more sophisticated case is when you have comments inside strings on a line, like in call("/*string*/"). Here is a script c-comments.sed, to solve this problem:

s:\(["][^"]*["]\):\n\1\n:g
s:/[*]:\n&:g
s:[*]/:&\n:g
:r
s:["]\([^\n]*\)\n\([^"]*\)":"\1\2":g
tr
:x
s:\(.*\)\n/[*]\([^\n]*\)[*]/\n\(.*\)$:\1\3 // \2:
s:\(.*\)\n\(.*\)//\(.*\)//\(.*\):\1\n\2 //\4\3:
tx
s:\n::g

您将此脚本保存到文件 c-comments.sed 中,并像这样调用它:

You save this script into a file c-comments.sed, and you call it like this:

sed -i -f c-comments.sed FILE

这篇关于sed 用 C++ 注释替换(单行)C 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆