Extract words before and after a pattern/regexp

Couldn't find much help on the kind of question I've here:
There is this text file with text as:

Line one has a bingo
Line two does not have a bingo but it has a tango
Bingo is on line three
Line four has both tango and bingo

Now I would want to search for the pattern "bingo" in this file and split the line to extract the words immediately preceding and following - "bingo".

Tried with this script using perl.. but my output file shows no result.

#! /usr/bin/perl

open (INFILE, "text1.txt");
open (OUTFILE,">outtext1.txt");

while (<INFILE>)
{
if (s/\w*(\w{1})bingo(\w{1})\w*/\1\2/) {
print OUTFILE;
}

}
close (INFILE);
close (OUTIFLE);

WIth this expression, I expect to get atleast the 2nd line to pass and the output file to have a but ['a bingo but']. But I get an empty outfile.

Can someone please point out how to accomplish this?

Thanks!

Hi,

I am not sure whether i have understood your req correcctly. Just try below awk script.

nawk '{
for(i=1;i<=NF;i++)
{
j=i+1
k=i-1
if($i=="bingo" && $j!="" && $k!="")
print $k" "$j
}
}' filename

Thanks Summer cherry! You got my question and nawk does the work, but can't we get this done by writing a simple regular expression?

Thanks again!

Hi.

Adjusting the RE in script file p1 to account for whitespace on either side of bingo, etc.:

#!/usr/bin/perl

use warnings;
use strict;

open( INFILE, "data1" ) || die " Can't open input file.\n";

while (<INFILE>) {
  if (s/.*(\w+)\s*bingo\s*(\w+).*/$1 $2/) {
    print;
  }

}

exit(0);

Producing:

% ./p1
a but

See man perlre for details ... cheers, drl