Thread nach dem Fund Zeilennummern auch zurückgeben (22 answers)
Opened by Henri at 2015-05-09 15:57

Linuxer
 2015-05-11 10:24
#180999 #180999
User since
2006-01-27
3875 Artikel
HausmeisterIn

user image
Naja, die zitierte Meldung ist auch nur eine Warnung, sollte aber dennoch beachtet werden. Soll das Komma wirklich Bestandteil des Suchwortes sein?

Wenn Du die Zeilennummer ausgeben willst, musst Du sie eben zwischenspeichern. Am besten geht das mit einem Hash of Arrays.

Code (perl): (dl )
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
#! /usr/bin/perl
use strict;
use warnings;

# words to search for
my @words = qw( wort1 wort2 wort3 wort4 );

# built a regex for the search; each word is to be treated as string
my $regex = join '|', map {"\Q${_}\E"} @words;          # list of alternative strings
$regex    = qr{($regex)};                               # capture the match

my %position;
while ( my $line = <DATA> ) {

        # save line number ($.) of each occurence in read lines;
        # use a while loop to catch multiple words in line
        push @{ $position{$1} }, $.     while $line =~ m{$regex}g; 
}

# show result
for my $word ( sort keys %position ) {
        printf "%s Zeile: %s\n", $word,join ", ", @{$position{$word}};
}



__DATA__
aaaa, aaaaa, aaaaaa, aaaaaa, wort1, aaaa, aaaa,
bbbbb, bbbbb, bbbb, wort2, bbbbb, bbbb, bbbbbb,
cccccc, ccccc, cccc, cccccc, wort3, cccc, cccc,
ddddd, dddddd, wort1, dddddd, ddddd, dddd, ddd,
eee, eee, eeeeee, eeeeeeee, wort4, wort2, eeee,


Ergebnis:
Code: (dl )
1
2
3
4
wort1 Zeile: 1, 4
wort2 Zeile: 2, 5
wort3 Zeile: 3
wort4 Zeile: 5

Last edited: 2015-05-11 10:25:48 +0200 (CEST)
meine Beiträge: I.d.R. alle Angaben ohne Gewähr und auf Linux abgestimmt!
Die Sprache heisst Perl, nicht PERL. - Bitte Crossposts als solche kenntlich machen!

View full thread nach dem Fund Zeilennummern auch zurückgeben