Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use echo with grep in a Unix shell script?

I need to use echo with grep in a shell script. Can I use it?

I tried this, but is incorrect:

echo Linux: grep "Linux" ~/workspace/ep-exercicios/m1/e2/intro-linux.html | wc -w

I need show the message:

Linux: (number of Linux word on the document).

Example:

Linux: 945
like image 772
Eric Saboia Avatar asked Jun 25 '16 03:06

Eric Saboia


3 Answers

Use grep with -o option:

printf "%s: %s\n" "Linux : " "$(grep -o "Linux" ~/workspace/ep-exercicios/m1/e2/intro-linux.html | wc -w)"

should do it

grep manpage says :

-o, --only-matching
Print only the matched (non-empty) parts of a matching line,with each such part on a separate output line.

like image 180
Мона_Сах Avatar answered Nov 20 '22 05:11

Мона_Сах


grep -o | wc -l logic from other answer should work on most systems today.

Here is another mechanism using awk.

awk 'END{print RS " : " NR-1}' RS=Linux ~/workspace/ep-exercicios/m1/e2/intro-linux.html

Logic: split the file in records, with record separator = "Linux". In the end, print the record number.


e.g. for file containing these contents:

The Linux is a Unix-like and mostly POSIX-compliant computer operating system (OS) assembled under the model of free and open-source software development and distribution. The defining component of Linux is the Linux kernel, an operating system kernel first released on October 5, 1991 by Linus Torvalds. The Free Software Foundation uses the name GNU/Linux to describe the operating system, which has led to some controversy

records will be:

  1. The
  2. is a Unix-like and mostly POSIX-compliant computer operating system (OS) assembled under the model of free and open-source software development and distribution. The defining component of
  3. is the
  4. kernel, an operating system kernel first released on October 5, 1991 by Linus Torvalds. The Free Software Foundation uses the name GNU/
  5. to describe the operating system, which has led to some controversy

Occurrence count of Linux is 4 == last record number - 1.

like image 3
anishsane Avatar answered Nov 20 '22 04:11

anishsane


Simply you can achieve it by doing slight modification below.

echo "Linux: `grep "Linux" ~/workspace/ep-exercicios/m1/e2/intro-linux.html | wc -w`"

like image 1
sailesh ramanam Avatar answered Nov 20 '22 04:11

sailesh ramanam