[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Einfuegen und Loeschen von Zeilen in einer Textdatei aus einem Shellscript



* Marc Haber  [28-04-2008 17:54]:

> foo-script --file=bar --insert="127.0.0.1"
> 
> eine Zeile hinzufügt (und zwar nur, wenn sie bereits existiert) und

Meinst du das wirklich so? Ich hätte jetzt erwartet, dass man die
Nummer hinzufügt, falls sie noch *nicht* existiert.

Ich habe mal in meinem Fundus gekrammt. Habe auch etwas gefunden,
und etwas angepasst. Schön machen musst du es selber. :-)

siehe Anhang

Gruß Uwe
#!/usr/bin/perl

use strict;
use warnings;
use IO::File;
use Getopt::Long;
use Fcntl qw(:flock);

use vars qw($opt_d $opt_f $opt_h $opt_i $opt_v);
GetOptions("d=s", "f=s", "i=s", "h", "v") || usage();
$| = 1;

sub usage {
    print "   options of script:\n\n";
    print "   -f XXX            logfile XXX\n";
    print "   -i XXX            insert number XXX\n";
    print "   -d XXX            delete number XXX\n";
    print "   -v                verbose\n";
    print "   -h                this help message\n\n";
    print "   syntax insert a number:\n";
    print "   script -f logfile -i 127.0.0.1\n\n";
    print "   syntax delete a number:\n";
    print "   script -f logfile -d 127.0.0.1\n\n";
    exit 0;
}

if ($opt_h) {
    usage();
}

if ($opt_f){
    if (! -f "$opt_f") {
	print "Info: touch $opt_f\n";
	system ("touch $opt_f");
    }
    if (! -f "$opt_f") {
	print "Error: file $opt_f not found!\n";
	exit 1;
    }
    my $file = IO::File->new("+<$opt_f");
    my @lines = ();
    if ($file) {
        flock($file, LOCK_EX);
        while (<$file>) {
	    my $line = $_;
	    if ($opt_v) {
		print "Verbose: read line: $line";
	    }
	    chomp $line;
	    if ($opt_i) {
		if ( $line =~ / \A $opt_i \z /xms ) {
		    print "Info: number $opt_i found.\n";
		    $file->close();
		    exit 0;
		}
	    }
	    push (@lines, $line);
	}
        seek($file, 0, 0);
        truncate($file, 0);
	foreach my $base (@lines) {
	    if ($opt_d) {
		if ( $base =~ / \A $opt_d \z /xms ) {
		    print "Info: delete number $opt_d now.\n";
		    next;
		}
	    }
            if ($opt_v) {
                print "Verbose: print line: $base\n";
            }	    
	    print {$file} "$base\n";
	}
	if ($opt_i) {
	    if ($opt_v) {
		print "Info: insert number $opt_i new.\n";
	    }
	    print {$file} "$opt_i\n";
	}
	$file->close();
    }
    else {
	print "Error: cannot open $opt_f: $!\n";
    }
    exit 0;
}

usage();

### eof

Attachment: signature.asc
Description: Digital signature


Reply to: