Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive multi-line replace: changing copyright headers

Tags:

replace

sed

awk

I'm retrying to replace all of the copyright headers in my project (100+ files) with a new version. Currently I have something like this at the start of each file:

<?php
/**
 * Project name
 *
 * @copyright Apache 2.0
 * @author    FooBar
 */

And I want all my files to start like this:

<?php
/**
 * Copyright 2014 FooBar
 *
 * 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
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */

I've already looked at:

  • this thread, which I can't get working. It does a partial replacement, keeping certain lines of the original text in the new text. I want a complete replacement.

  • this script, which similarly doesn't work for my use case. It replaces the very start of each file with a new header, which causes the existing content (<?php /** */) to be appended to the new comment, thereby causing parse errors.

Does anybody know how I can do a recursive multi-line file replace? Do I need to use sed/awk?

SOLUTION:

I just need to execute this bash script:

INPUT=../path

find $INPUT -name "*.php" -exec sed -i -e '2,/\*\//d; 1r copyright.txt' {} \;
like image 648
hohner Avatar asked Mar 26 '26 17:03

hohner


2 Answers

Is it safe to assume all your files start with

<?php
/**

If so, you can use

sed '2,/\*\//d; 1r newSig.txt' input.txt

The first sed command deletes the signature from line 2 til the end of the signature. You could use a dynamic range but it would also delete other multi-line signatures in the file. The second command reads the file newSig.txt, which has your new signature, and appends it after line 1.

like image 99
pfnuesel Avatar answered Mar 29 '26 15:03

pfnuesel


With GNU awk for a multi-char RS to read the whole file as a single string:

$ 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
 */
like image 40
Ed Morton Avatar answered Mar 29 '26 15:03

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!