1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
#! /usr/bin/perl
# Addenty 0.2 by Marco Pistore
# Adds (and removes) entries of a "KEY=v1 v2 v3 .. vn" list in a file
#
# Copyright 1998 by Marco Pistore.
# I hereby give you perpetual unlimited permission to copy,
# modify, sell and relicense this file, provided that you do not remove
# my name from the file itself. (I assert my moral right of
# paternity under the Copyright, Designs and Patents Act 1988.)
$program=addentry;
$version=0.2;
$remove=0;
$print_help=0;
$verbose=0;
while ($_ = $ARGV[0], /^-/) {
shift;
last if /^--$/;
if (/^-V$/ || /^--version$/ || /^-h$/ || /^--help$/) {
$print_help=1;
} elsif (/^-r$/ || /^--remove$/) {
$remove=1;
} elsif (/^-a$/ || /^--add$/) {
$remove=0;
} else {
die "Invalid parameter: $_. Stopped";
}
}
if ($print_help) {
print "This is $program $version, by Marco Pistore <pistore\@di.unipi.it>!\n";
print "Usage: $program [--remove] FILE KEY ENTRY [... ENTRY]\n";
exit 0;
}
die "No file is specifed. Stopped" if (@ARGV == 0);
$file = $ARGV[0];
$tmpfile = "$file.tmp";
shift;
die "No key is specifed. Stopped" if (@ARGV == 0);
$key = $ARGV[0];
shift;
die "No entry is specifed. Stopped" if (@ARGV == 0);
open (INFILE, "<$file") or die "Cannot open file $file. Stopped";
open (OUTFILE, ">$tmpfile") or die "Cannot open file $tmpfile. Stopped";
$found=0;
LINE: while (<INFILE>) {
do {
chomp;
foreach $el (@ARGV) {
if ($remove) {
$_="$1$3" if /^($key=.*?)(\s*\b$el\b)(.*)$/;
} else {
$_="$_ $el" if ! /^$key=.*\b$el\b/;
}
}
$_="$_\n";
print OUTFILE;
$found=1;
while(<INFILE>) { print OUTFILE; }
last LINE;
} if /^$key=/;
print OUTFILE;
}
close INFILE;
close OUTFILE;
die "Key $key not found in $file. Stopped" if ! $found;
rename ($tmpfile, $file) or die "Cannot copy $tmpfile to $file. Stopped";
|