tags:

views:

80

answers:

4

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 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"
    }  
} 
A: 
#!/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";
        }
    }
}
ghostdog74
Doesn't work if "ddd" is the first/last word, or the only word.
eugene y
+1  A: 
#!/usr/bin/perl -w
while (<>) {
    if (/((?:[a-z]{3} )?ddd(?: [a-z]{3})?)/)
        print "$1\n";
}
ptomli
+3  A: 

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.
codaddict
+1  A: 
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";
        }
    }

}
eugene y