Skip to content

Instantly share code, notes, and snippets.

@derlin
Last active August 16, 2016 09:18
Show Gist options
  • Save derlin/1200d89af0330f7afdeb2bb0c4fe1ee9 to your computer and use it in GitHub Desktop.
Save derlin/1200d89af0330f7afdeb2bb0c4fe1ee9 to your computer and use it in GitHub Desktop.
Perl script to add headers to the top of source files.
#!/usr/bin/env perl
# add headers at the top of files
# how to use:
# perl add-headers.pl <header file> files
# to add headers to cpp files recursively, use:
# perl add-headers.pl $(find . -name "*.cpp")
# beware: the script does not check if the file already contains headers !
$cnt = 0;
$header = "";
while (<>) {
$line = $_;
if ($ARGV ne $oldargv) { # are we at the next file?
if($cnt > 0){
# rename($ARGV, $ARGV . '.orig'); # if we want a .orig backup
open(ARGVOUT, ">$ARGV"); # plus error check
select(ARGVOUT);
print "$header \n";
}
$oldargv = $ARGV;
$cnt++;
}
$header .= $line if $cnt == 1;
print $line;
}
select (STDOUT); # restore default output
#!/usr/bin/env perl
# remove headers and blank lines at the top of files
# how to use:
# perl remove-headers.pl files
# to remove headers from cpp files recursively, use:
# perl remove-headers.pl $(find . -name "*.cpp")
while (<>) {
$line = $_;
if ($ARGV ne $oldargv) { # are we at the next file?
# rename($ARGV, $ARGV . '.orig'); # if we want a .orig backup
open(ARGVOUT, ">$ARGV"); # plus error check
select(ARGVOUT);
$oldargv = $ARGV;
$print = 0; # skip blanks and headers at the top of the file
}
# header if only blanks since the beginning of the file and /**
$header = 1 if not $print and $line =~ /^\s*\/\*\*/;
# if in header, just detect the end "**/"
if($header){
$header = 0 if $line =~ /\*\*\*\//;
}else{
# not in header: begin printing after the last blank line
$print = 1 if $line !~ /^\s*$/;
print $line if $print;
}
}
select (STDOUT); # restore default output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment