0

我知道如何删除所有评论或删除文件中的指定行,但不知道如何只删除包含作者、版权等的第一条顶级评论行。我不能只使用删除第一行,因为可能有源文件根本不包含顶级评论块。有什么建议吗?

更新:源文件是objective-c文件,所有顶级注释行都以//. 可能规则“删除所有评论行,直到找到第一个非评论行然后停止”最能描述我想要实现的目标。

第二个问题:另外,寻找一种方法来告诉 sed 通过所有项目目录和文件递归循环。

更新2。这是我正在尝试修改的objective-c文件的注释块示例:

//
//  MyProjectAppDelegate.m
//  MyProject
//
//  Created by Name Surname on 2011-09-20.
//  Copyright 2012 JSC MyCompany. All rights reserved.
//
4

3 回答 3

2

如果 awk 也被接受,请查看以下内容:

 awk 'BEGIN{f=1}f&&/^\/\//{next;}{f=0}1' yourFile

测试

kent$  cat test.txt
//
//  MyProjectAppDelegate.m
//  MyProject
//
//  Created by Name Surname on 2011-09-20.
//  Copyright 2012 JSC MyCompany. All rights reserved.
//
real codes come here...

// comments in codes should be kept

foo bar foo bar


kent$  awk 'BEGIN{f=1}f&&/^\/\//{next;}{f=0}1' test.txt
real codes come here...

// comments in codes should be kept

foo bar foo bar

您可以结合 find 和 awk one-liner 进行递归处理。

sed 也可以用同样的想法做到这一点。需要在Hold space写一个标记,并检查每一行的hold space。它具有 -i 选项的优势,它允许您更改原始文件。但是我觉得 awk 更直接地完成这项工作。将更改的文本保存回原始文件也不是一件难事。

于 2012-09-19T09:59:07.987 回答
1

这是一个适用于Kent'ssed的解决方案: test.txt

sed -n '/^ *\/\//! { :a;p;N;s/.*\n//;ba}'

输出:

real codes come here...

// comments in codes should be kept

foo bar foo bar

解释

sed -n '/^ *\/\//!{    # if line does not start with //
  :a                   # label a
  p                    # print line
  N                    # append next line to PS
  s/.*\n//             # remove previous line
  ba                   # branch to a
}' < test.txt
于 2012-09-19T10:50:03.607 回答
1

试试看:

sed '0,\#^\([^/]\|/[^/]\)\|^$# d'
于 2012-09-19T11:23:47.373 回答