0

To a file jungle.txt with following text ...

A lion sleeps in the jungle
A lion sleeps tonight
A tiger awakens in the swamp
The parrot observes
Wimoweh, wimoweh, wimoweh, wimoweh

... one could perform GREP search ...

$ grep lion jungle.txt

... or SED search ...

$ sed "/lion/p" jungle.txt

... to find occurences of a pattern ("lion" in this case).

Is there some easy way to get a number of returned lines? Or at least to know that there was more than 1 found? As always, I've googled a lot first, but surprisingly found no answer.

Thanks!

Petr Cibulka
  • 2,452
  • 4
  • 28
  • 45

4 Answers4

6

grep can count matching lines:

grep -c 'lion' file

Output:

2

Syntax:

-c: Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines. (-c is specified by POSIX.)

Cyrus
  • 84,225
  • 14
  • 89
  • 153
2

This might work for you (GNU sed):

sed '/lion/!d' file | sed '$=;d'

or if you prefer:

sed -n '/lion/p' file | sed -n '$='

N.B. if the file is empty or the first sed command finds nothing the result of the second sed command is blank.

potong
  • 55,640
  • 6
  • 51
  • 83
2

You can use awk

awk '/lion/ {a++} END {print a+0}'
2

But I would say that the best solution is the one posted by Cyros using grep -c 'lion' file

Jotne
  • 40,548
  • 12
  • 51
  • 55
  • 1
    You need to make it `print a+0` to get 0 printed instead of a null string if the RE doesn't exist in the file. – Ed Morton Sep 01 '14 at 15:45
1

Just pass the grep command output to wc- l command to count the number of returned lines,

$ grep 'lion' file | wc -l
2

From wc --help

-l, --lines            print the newline counts
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274