How to limit the search to 'n' occurrences within a line

Hello All,

I am trying to search one pattern across a file and then print it. But i need to delimit the search per line to 2 occurrences. How do i do that?

Regards.

Try...

 
awk -v var="searchstring" '{str=$0;cnt=gsub(var,arr);if(cnt==2)print str}' infile
perl -nle '{print $_ if scalar(@_ = $_ =~ /pattern/g) == 2}' infile

Hello malcomex999, Vi-Curious,

Thanks for the replies.I tried both the suggestions but none of them worked for me :-(. My file contains -

~/Desktop$ cat b.txt
hello hello hello hello
good morning
good evening

I am trying to search for hello string in this file and am expecting it to print 'hello' only twice in the output. Please let me know if i am doing something wrong there.

~/Desktop$ awk -v var="hello" '{str=$0;cnt=gsub(var,arr);if(cnt==2)print str}' b.txt
<No OutPut here>

~/Desktop$ perl -nle '{print $_ if scalar(@_ == $_ =~ /hello/g) == 2}' b.txt
<No OutPut here>

Regards.

A slight modification in the Vi-Curious does the trick.

perl -nle '{print "$_[0] $_[1]" if (@_ = $_ =~ /hello/g) }' b.txt

Or awk...

 
awk -v var="hello" '{cnt=gsub(var,arr);if(cnt>=2)print var,var}' infile

The reason there was no output was because the first occurrence of == in your example should have been just a single =. Others have already posted follow-up examples to your latest query so I'll just say that this would have printed the entire line if it contained exactly 2 occurrences of the search pattern. It wasn't clear from your initial post that you wanted to print out the first 2 occurrences of (only) the search pattern if it occurred 2 or more times in the line.

Hello All,

I am not familiar with the perl and awk syntax :-(.

Thanks a lot! It worked as expected !

Regards.

try google

The example I posted:

 perl -nle '{print $_ if scalar(@_ = $_ =~ /pattern/g) == 2}' infile
perl -nle 'expression' infile

loop over the file 'infile' and execute 'expression' on each line

$_ =~ /pattern/g

Bind to the current line ($) and search for all occurences of pattern on that line. By default, this operation will work on $ so that could have been omitted and this part could have been specified as /pattern/g.

@_ = $_ =~ /pattern/g

In list context, m//g, or simply //g, returns all of the matched occurrences of pattern. So @_ will be a list containing however many occurrences of the pattern existed.

scalar(@_ = ... )

Take the list @_ and tell me how many items it contains.

if scalar(...) == 2

Check to see if it contains 2 items (occurrences of pattern).

print $_ if scalar(...) == 2

Print the current line from the file if it contains exactly 2 occurrences of the search pattern.... which is what I thought you wanted.

Thanks Vi-Curious,

Yes. Will google and learn more :slight_smile:

Thanks for the detailed explanation!

Regards.