简体   繁体   English

Unix shell脚本中如何在grep中使用echo?

[英]How use echo with grep in a Unix shell script?

I need to use echo with grep in a shell script. 我需要在shell脚本中将echo与grep一起使用。 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

Use grep with -o option: grep-o选项一起使用:

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

should do it 应该做

grep manpage says : grep手册页说:

-o, --only-matching -o,--only-matching
Print only the matched (non-empty) parts of a matching line,with each such part on a separate output line. 仅打印匹配行的匹配(非空)部分,每个这样的部分都在单独的输出行上。

grep -o | wc -l grep -o | wc -l logic from other answer should work on most systems today. 如今,其他答案中的grep -o | wc -l逻辑应该可以在大多数系统上运行。

Here is another mechanism using awk . 这是使用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". 逻辑:使用记录分隔符=“ Linux”将文件拆分为记录。 In the end, print the record number. 最后,打印记录号。


eg 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. Linux是一种类似于Unix且主要与POSIX兼容的计算机操作系统(OS),以自由和开源软件开发和发行的模式进行组装。 The defining component of Linux is the Linux kernel, an operating system kernel first released on October 5, 1991 by Linus Torvalds. Linux的定义组件是Linux内核,它是Linus Torvalds于1991年10月5日首次发布的操作系统内核。 The Free Software Foundation uses the name GNU/Linux to describe the operating system, which has led to some controversy 自由软件基金会使用名称GNU / Linux来描述操作系统,这引起了一些争议。

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. 是在自由和开源软件开发和发行模型下组装的,类似于Unix且主要与POSIX兼容的计算机操作系统(OS)。 The defining component of 的定义部分
  3. is the 是个
  4. kernel, an operating system kernel first released on October 5, 1991 by Linus Torvalds. 内核,Linus Torvalds于1991年10月5日首次发布的操作系统内核。 The Free Software Foundation uses the name GNU/ 自由软件基金会使用名称GNU /
  5. to describe the operating system, which has led to some controversy 描述操作系统,这引起了一些争议

Occurrence count of Linux is 4 == last record number - 1. Linux的出现次数是4 ==最后记录数-1。

Simply you can achieve it by doing slight modification below. 只需在下面进行一些修改即可实现。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM