替换每个文件中的许可证通知

时间:2012-12-17 09:15:48

标签: linux unix sed awk replace

我想在一个相对较大的项目的每个文件的顶部替换多行许可证通知(从GNU GPLApache 2.0)。许可声明包含几个段落。另一个要求是目标许可证通知中有一个占位符取决于当前文件名,因此简单的查找和替换是不够的。

我很熟悉:

find . -name "*.java" -exec sed -i 's/find/replace/g' {} \;

但是我看不出如何使它适用于这个用例。

更新:

目标Apache 2.0许可证的占位符如下所示:

Copyright [yyyy] [name of copyright owner]
[filename.java] <br/><br/>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at<br/><br/>

http://www.apache.org/licenses/LICENSE-2.0<br/><br/>

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

3 个答案:

答案 0 :(得分:2)

我知道clicki-buntis并不总是更好,但在这种情况下我使用'kfilereplace'。它是专为此目的而设计的kde工具。它允许您设置正则表达式并运行模拟传递。这样您就可以先测试您的设置,然后进行“实时”替换。

占位符:

  • 进行两次更换,分别更换占位符前后的部分。这样你只需要替换两个静态字符串,没有动态。
  • 使用占位符替换策略,许多正则表达式替换函数提供接管要替换的文本的动态占位符部分。

答案 1 :(得分:2)

使用以下sed命令删除从start_pattern开始到以end_pattern结尾的行:

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

例如,要删除GNU GPL许可证,您可以使用:

sed -n '/GNU GENERAL PUBLIC LICENSE/{:a;N;/why-not-lgpl.html\>./!ba;N;s/.*\n//};p' file

要使用findxargs

一起在多个文件上运行此操作
find . -name "*.java" -print0 | xargs -0 sed -i -n '/GNU GENERAL PUBLIC LICENSE/{:a;N;/why-not-lgpl.html\>./!ba;N;s/.*\n//};p'

答案 2 :(得分:1)

的Perl:

# First, get the text for the Apache license, stick it in a shell variable:
export APACHE="$(curl -s http://www.apache.org/licenses/LICENSE-2.0.txt)"


# For a single file:
perl -p -i -e 'BEGIN{undef $/} 
  s#GNU GENERAL PUBLIC LICENSE.*<http://www.gnu.org/philosophy/why-not-lgpl.html>.# Copyright... [$ARGV] <br/> ... $ENV{APACHE}#smg' A.java

注意事项:

  1. 在Perl中,$ARGV包含文件名(当前正在处理的输入文件)
  2. 我猜您可以find使用xargs递归执行此操作。

    find . -name "*.java" | xargs -l1 perl ....