Replace 递归多行替换:更改版权标题
我正在尝试用新版本替换项目中的所有版权标题(100多个文件)。目前,我在每个文件的开头都有类似的内容:Replace 递归多行替换:更改版权标题,replace,sed,awk,Replace,Sed,Awk,我正在尝试用新版本替换项目中的所有版权标题(100多个文件)。目前,我在每个文件的开头都有类似的内容: <?php /** * Project name * * @copyright Apache 2.0 * @author FooBar */ 假设您的所有文件都以 <?php /** 第一个命令从第2行删除签名,直到签名结束。您可以使用动态范围,但它也会删除文件中的其他多行签名。第二个命令读取包含新签名的文件newSig.txt,并将其附加在第1行之后。注意:您
<?php
/**
* Project name
*
* @copyright Apache 2.0
* @author FooBar
*/
假设您的所有文件都以
<?php
/**
第一个命令从第2行删除签名,直到签名结束。您可以使用动态范围,但它也会删除文件中的其他多行签名。第二个命令读取包含新签名的文件newSig.txt
,并将其附加在第1行之后。注意:您也应该阅读。考虑到这是一个问题,在运行awk脚本之前,您可以检查文件并只将可读的文件传递给循环
如果您的文件总是这样开始,使用gawk
解决它的一种方法是
awk 'FNR==1 { print $0
print "INSERT YOUR new header here even on multiline print statements."
# if you don't mind your old header, stop here and skip the below rules
}
FNR==2 && $0 ~ "/\*\*" {
while (getline) {
if ($0 == "*/") { getline ; break }
}
}
FNR>2 { print $0 }' INPUTFILE
您可以将其包装在循环中,如
for file in *php ; do
awk ... $file > $file.new
done
我的方式是没有限制的固定线路
<?php
/**
3) 如果没有问题,则在所有php文件上运行脚本:
for file in *.php
do
sed ':a;$!{N;ba};s!/[^/]*/!########!1' $file|sed -e '/########/{r update.txt' -e 'd}' > temp
mv temp "$file"
done
使用GNU awk,多字符RS可以将整个文件作为单个字符串读取:
$ gawk -v RS='^$' -v hdr="\
/**
* Copyright 2014 FooBar
*
* Licensed under the blah blah blah
*/\
" '{sub(/\/\*[^/]+\*\//,hdr)}1' file
<?php
/**
* Copyright 2014 FooBar
*
* Licensed under the blah blah blah
*/
$gawk-vrs='^$'-vhdr='\
/**
*版权所有2014 FooBar
*
*根据废话废话获得许可
*/\
“{sub(/\/\*[^/]+\*\//,hdr)}1”文件
在这个问题上,你所说的“递归”是什么意思?它应该以什么方式递归,为什么?当它第一次遇到无法打开的文件时,它将进入无限循环。如果您正在考虑使用getline
,请确保您阅读并完全理解所有的注意事项和适当的应用程序(这不是其中之一)。您总是对的@EdMorton,我正在编辑这篇文章。
<?php
/**
sed ':a;$!{N;ba};s!/[^/]*/!########!1' abc.php|sed -e '/########/{r update.txt' -e 'd}'
for file in *.php
do
sed ':a;$!{N;ba};s!/[^/]*/!########!1' $file|sed -e '/########/{r update.txt' -e 'd}' > temp
mv temp "$file"
done
$ gawk -v RS='^$' -v hdr="\
/**
* Copyright 2014 FooBar
*
* Licensed under the blah blah blah
*/\
" '{sub(/\/\*[^/]+\*\//,hdr)}1' file
<?php
/**
* Copyright 2014 FooBar
*
* Licensed under the blah blah blah
*/