1

How can i count number of lines having the word -> [com.java.Name abc] <- in a text file based on certain date and time

I tried below but showing only 1 the value. Expected there is 4 lines. It should count based on lines not word. How can i mention the date and time as well

grep -c '[com.java.Name abc]' server.log | wc -l

Below is the sample file

2020-06-14 13:46:10,442 INFO  [com.java.Name abc] [com.java.Name abc]
2020-06-14 13:46:20,420 INFO  [com.java.Name abc]
2020-06-14 13:47:14,410 INFO  [com.java.Name abc]
2020-06-14 13:48:12,442 INFO  [com.java.Name abc]

jake
  • 13
  • Do you know the exact timestamp as it occurs in your logfile, or do you want to "look for occurence of a specific pattern somewhere between timestamp 1 and timestamp 2? – AdminBee Jun 15 '20 at 07:59

2 Answers2

2

The -c grep option already does the count. So the result of the grep is a single number. Hence wc will of course only find one line. Just remove the wc altogether.

kaylum
  • 531
  • 3
  • 6
  • 1
    I already tried.. if i put grep -c '[com.java.Name abc]' server.log i get 20700 which not correct however when i try grep -c 'com.java.Name abc' server.log i get 4 lines. why is is like that? and how to perform based on certai ndate and time –  Jun 15 '20 at 05:19
1

The problem with your approach is that you are looking for a pattern which contains [ and ]. These have a special meaning in regular expressions, namely they are "character lists" and match any character enclosed in them. So, performing

grep '[com.java.Name abc]' logfile

would match any line containing any of the characters a, b, c, e, j, m, o, v, N, the space, and the period ., regardless of their location on the line (which likely matches every line of the log file).

You need to escape the [ and ], as in

grep -c '\[com.java.Name abc\]' logfile

or - as pointed out by @terdon - use the -F flag:

grep -c -F '[com.java.Name abc]' logfile

If you want to look for occurences at a certain date, the mechanism depends. If you know the day, say 2020-06-14, it could be as easy as stating

grep -c '^2020-06-14.*\[com.java.Name abc\]' logfile

If you want to search based on the full timestamp, that approach would only work if you knew the exact moment as it is formatted in the logfile, as in

grep -c '^2020-06-14 13:48:12,442.*\[com.java.Name abc\]' logfile

which is unlikely because then you probably wouldn't need to count the occurences in the first place. In that case, you could try to adapt some of the following answers:

AdminBee
  • 22,803