【问题标题】:Shell script to search for a word in a while block of the C program用于在 C 程序的 while 块中搜索单词的 Shell 脚本
【发布时间】:2015-01-09 02:25:04
【问题描述】:

我想在文件中搜索单词“while”,如果文件包含该单词,那么在给定的块中我需要搜索另一个单词“Hello”,如果 hello 存在,那么它的行 no 应该是打印出来的。

请在这方面提供帮助 提前致谢。

【问题讨论】:

  • 你能举个例子吗?
  • code while (condition) { How old are you HelloHoware you } Hello code 现在在这种情况下,应该只打印第 4 行,因为它在 while 块中包含 Hello。
  • 我见过多行while函数。
  • 请编辑您的问题以包含示例 - 它不可读或作为评论有用。
  • 停止尝试将格式化文本放入 cmets,因为您根本做不到。您需要编辑您的问题以添加您尝试向我们展示的任何格式化文本。

标签: shell awk sed scripting


【解决方案1】:

像这样的?

cat file
Hi

This is a bloc
It may have while word
Here is Hello too

In this block
we have while
but not the other word

awk -v RS="" '/while/ && /Hello/' file
This is a bloc
It may have while word
Here is Hello too

这里每个块都由一个空行分隔。
要使awk 以块方式工作,请将RS 设置为空。
然后搜索包含whileHello 的所有行


如果你想在整个文件中搜索while,如果找到了,打印带有Hello的块,这样做:

awk -v RS="" 'FNR==NR && /while/ {f=1;next} f && /Hello/'  file file

这两次读取file。第一次搜索while,如果找到则设置f
第二次,如果f 为真,并且找到Hello,则打印块。

【讨论】:

  • 我认为您错过了问题的重点 - 他正在 C 程序中的 while (condition) { body } 块中查找单词。
猜你喜欢
  • 2022-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多