Print matching lines in a file

Hello everyone,

I have a little script below:

die "Usage infile outfile reGex" if @ARGV != 3;
($regex) = @ARGV;

open(F,$ARGV[0]) or die "Can't open";
open(FOUT,"+>$ARGV[1]") or die "Can't open";

while (<F>)
{
  print FOUT if /$regex/.../$regex/;
}

No matter what I give $regex on the command line, it will only print to FOUT the first 3 line of F. Can anyone tell me what I do wrong here. I want to print out all lines matches whatever I give $regex on the command line.

Appreciate any help,

New bie

I assumed you passed three arguments in the program.

Argument 1 : input file
Argument 2 : output file
Argument 3 : your regex

($regex) = @ARGV;

For the above code $regex get the input file name only. So you not able get the desired output. You must assign the third argument as $regex.

I slightly modify your code. Try this

die "Usage infile outfile reGex" if @ARGV != 3;
($regex) = $ARGV[2];
open(F,$ARGV[0]) or die "Can't open";
open(FOUT,"+>$ARGV[1]") or die "Can't open";
while (<F>)
{
  # $_ is a default variable
  # if your regex match the line you get the line into $ARGV[1] file
  print FOUT "$_" if ($_ =~ /$regex/);
}

Thank you so much K_Manimuthu, your explanation really help me understand the process when assign to @ARGV, really appreciate it.

New bie