Pattern count in file

hi ,

I have a below file which contain as

Use descriptive thread titles when posting Urgent. 

For example, do not post  questions with subjects like "Help Me!", "Urgent Urgent Urgent" .

or "Doubt". Post  subjects like "Execution Problems with Cron" or "Help with Backup Shell  Script". See new thread posting rules at the top of this page. 

Thanks! 

I want the keyword Urgent pattern count in each line in my file

Can you give 1-2 more example files, describe exactly what the output should be and enclose the output as you want it to be for the different example files?

1 Like

The following prefixes each line with the number of matches

 awk '{x=$0; print gsub("\<Urgent\>","",x),$0}' file

my output would be like below..

Line :1
Line 2: 3
line 3 :0
Line 4 : 0

You have shown us a seven line sample input file and you have shown us a sample output file with four lines. If you wanted the code to ignore empty lines, or to ignore blank lines, or to ignore lines with no occurrences of your keyword until you have found two lines containing your key word and then print no more than two lines containing zero occurrences of your key word; don't you think think you should explain what criteria should be used to determine which lines are to be processed or counted or numbered???

Why isn't the line number supposed to be included in the 1st line of output? Why is there a space before the colon sometimes and a space after the colon sometimes in the output.

Please, give it a try:

perl -nle  '$c=()=$_=~/Urgent/g; printf "Line $.: %d\n", $c' Jewel.file

Output:

Line 1: 1
Line 2: 3
Line 3: 0
Line 4: 0
awk 'NF {print "Line " ++l ": " gsub("Urgent", "&")}' infile

Thanks friends. it workking