ADAPA NIKHIL
ADAPA NIKHIL

Reputation: 57

check for a pattern from a line in file and count the number of lines which are matching the pattern

I am having a directory called checks and in that a file called true.txt as below:

Column1     column2     column3     column4     column5
Data        25          gen(*)      87          65  
Stem        34          gen(*)      23          76
Invert      36          gen($)      89          67
Delete      32          gen($)      43          23
print       34          gen(*)      34          34
ctrl        23          gen($)      33          43

I need to count the number of lines containing gen(*) and number of lines contaiing gen($), irrespective of column1, and in some situations in column3 gen($) may not there then I need to print it as zero, I shared the output syntax for reference and desired output like below:

output syntax:
Directoryname : count of gen($)     count of gen(*)

output:
checks : 3  3

I tried this code but not getting the exact output:

#!/bin/bash
for d in checks
awk 'BEGIN
FNR==NR
/gen \(\*\)/{
  tot=FNR
  next
}
END{
  print "checks : ",tot-1
}
' true.txt

Upvotes: 0

Views: 92

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following. Written and tested link https://ideone.com/xBrCzc

awk '
$3=="gen(*)"{ countGenstar++ }
$3=="gen($)"{ countGendollar++ }
END{
  print "Count: ",countGenstar+0,countGendollar+0
}' Input_file

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203229

$ awk '
    { cnt[$3]++ }
    END {
        dir = FILENAME
        sub("/[^/]+$","",dir)
        sub(".*/","",dir)
        print dir, ":", cnt["gen($)"]+0, cnt["gen(*)"]+0
    }
' $HOME/checks/true.txt
checks : 3 3

Upvotes: 0

Dominique
Dominique

Reputation: 17493

Is there a reason you need this to be done using only awk?
Grep can solve this problem very easily:

fgrep -c "gen(*)" true.txt
fgrep -c "gen($)" true.txt

In case you don't have fgrep, it's the same as grep -F.

Upvotes: 0

Related Questions