RandomUser RandomUser - 6 months ago 14
Bash Question

Print line having two instances of same string in same line

I am trying to print lines which are having N(2 in this case) number of patterns in it.

For example: (input file)

cat data.txt
hello all
this is a text file
and this line is having one pattern
and this line is having two pattern, and here is another one : pattern. so its two in this line.
in this line pattern is three times , here is two more pattern and pattern


output: (print line containing two strings = pattern)

and this line is having two pattern, and here is another one : pattern. so its two in this line.


I was trying in following direction ,but
grep -c
is not helping me here.

string=pattern
while read line
do

count=$(echo $line |grep -c $string)
#this always gives me 1, as its a count based on line.
if [ "$count" -eq 2 ];then
echo $line
fi

done <data.txt


any suggestions ?

123 123
Answer

Using awk

awk 'gsub(/pattern/,"&")==2' file

if you want to pass in the params

awk -vPattern="pattern" -vNum=2 'gsub(Pattern,"&")==Num' file