Extract word between two KEYWORDS

Hi
I want to extract all the words between two keywords HELLO & BYE.

eg:
Input

1_HELLO_HOW_ARE_YOU_BYE_TEST
1_HELLO_WHERE_ARE_BYE_TEST
1_HELLO_HOW_BYE_TEST

Output Required:

HOW_ARE_YOU
WHERE_ARE
HOW
awk -F"HELLO_" '{print $2}' filename | awk -F"_BYE" '{print $1}'
1 Like

Thanks...
However I have to implement this in PERL script.
So when I am using it like

$var1 = `awk -F"HELLO_" '{print $2}' filename | awk -F"_BYE" '{print $1}'`

I am getting error:

Use of uninitialized value $2 in concatenation (.) or string.
Use of uninitialized value $1 in concatenation (.) or string.

Kindly assist.

You can use below code in sed

 
sed 's/1_HELLO_\(.*\)_BYE\(.*\)/\1/g' filename
 
bash-3.00$ sed 's/1_HELLO_\(.*\)_BYE\(.*\)/\1/g' a
HOW_ARE_YOU
WHERE_ARE
HOW

$ perl -pe 's/.+HELLO_(.+)_BYE.+/\1/' file
HOW_ARE_YOU
WHERE_ARE
HOW

Hi Rajamadhavan

Thanks for prompt reply.
How to assign the output to a variable in PERL ? [Assuming I will get only one line]

Another way with assigning to variable

open(FILE, "<file") || die;
my $var;
while(<FILE>) {
      $_ =~ m/.+HELLO_(.+)_BYE.+/g;  
      $var = $1;
      print $var;
}

Thanks to all.
It worked fine.
All the suggestions worked perfectly fine. :slight_smile: