用于添加或替换 .c 、 .h 和 makefile 中包含的许可证文本的 Shell 脚本 (bash)?

Thu*_*shi 5 shell-script text-processing

我在一个文件夹中有一组 *.c 、 *.h 和 Makefile,其中一些文件包含许可证文本,而一些文件没有任何许可证文本。所以我需要一个 shell 脚本,如果文件没有任何许可文本,我可以在其中添加许可文本,如果许可文本已经存在,那么我想用新的许可文本替换它。

例如

Folder1
?? *.c
?? *.h
?? Folder2
?  ?? *.c
?  ?? *.h
?  ?? Makefiles
?  ?? Folder4
?? Folder3
   ?? *.c
   ?? *.h
   ?? Makefiles
Run Code Online (Sandbox Code Playgroud)

注意:许可证文本将始终位于文件的开头。

现有许可证文本示例:

# Copyright (C) 2008 Jack <abc@cba.com>

# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
Run Code Online (Sandbox Code Playgroud)

新的许可证文本应该是:

/*---------------------------------------------------------------------

Copyright © 2014  Author Name

All rights reserved

----------------------------------------------------------------------*/
Run Code Online (Sandbox Code Playgroud)

对于 Makefile,它应该是:

# ---------------------------------------------------------------------
# Copyright © 2014  Author Name
#
# All rights reserved
# ----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

gle*_*man 6

假设 bash:

function remove_copyright {
    printf "%s\n" 1,10d w q | ed "$1"
}

function add_copyright {
    if [[ $1 == Makefile ]]; then
        ed "$1" <<END
0i
# ---------------------------------------------------------------------
# Copyright © 2014  Author Name
#
# All rights reserved
# ---------------------------------------------------------------------
.
w
q
END
    else
        ed "$1" <<END
0i
/*---------------------------------------------------------------------

Copyright © 2014  Author Name

All rights reserved

---------------------------------------------------------------------*/
.
w
q
END
    fi
}

shopt -s nullglob globstar
for file in **/*.[ch]; do
    if grep -q '^# Copyright \(C\)' "$file"; then
        remove_copyright "$file"
    fi
    add_copyright "$file"
done
Run Code Online (Sandbox Code Playgroud)