开发者

Extract the surrounding words together with the match

开发者 https://www.devze.com 2022-12-22 15:00 出处:网络
I am looking for every occurence of a search term, e.g. ddd, in a file and output the surroundings, like this:

I am looking for every occurence of a search term, e.g. ddd, in a file and output the surroundings, like this:

File.txt

aaa bbb ccc ddd eee fff
ttt uuu iii eee ddd
ddd
ggg jjj kkk 开发者_JAVA百科ddd lll

output

ccc ddd eee
eee ddd
ddd
kkk ddd lll

As a starting point, I am using this piece of code

#!/usr/bin/perl -w     
while(<>) { 
    while (/ddd(\d{1,3}))/g) {       
    print "$1\n"
    }  
} 


You can try the following..it gives the output you want:

while(<>) {
        if(/((?:\w+ )?ddd(?: \w+)?)/) {
                print "$1\n";
        }
}

Regex used:

(         # open the grouping.
(?:\w+ )? # an optional word of at least one char followed by a space.
ddd       #  'ddd'
(?: \w+)? # an optional space followed by a word of at least one char.
)         # close the grouping.


#!/usr/bin/perl -w
while (<>) {
    if (/((?:[a-z]{3} )?ddd(?: [a-z]{3})?)/)
        print "$1\n";
}


while (<>) {  
    chomp;
    my @words = split;
    for my $i (0..$#words) {
        if ($words[$i] eq 'ddd') {
            print join ' ', $i > 0 ? $words[$i-1] : (), $words[$i], $i < $#words ? $words[$i+1] : ();
            print "\n";
        }
    }

}


#!/usr/bin/perl

while (<>) {
    chomp;
    @F = split /\s+/;
    if (/^ddd$/) {print $_."\n";next};
    for ($i=0; $i<=$#F;$i++) {
        if ($F[$i] eq 'ddd') {
            print "$F[$i-1] $F[$i] $F[$i + 1]\n";
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消