在linux中,如何添加print语句来计算包含关键字的行数
假设我有输入文件:在linux中,如何添加print语句来计算包含关键字的行数,linux,Linux,假设我有输入文件: 你好你好 你好你好 你好你好 你好你好 你好你好 b dr t 4 t 我希望能够打印出包含hello的n行,以及另外一行“找到了包含hello的n行” 我已经开始使用grep命令“grep hello.txt” 我知道“wc-l”查找输出有多少行。 我的想法是以某种方式使用sed工具进行管道连接,尽管我不太确定如何进行 使用awk,而不是sed: $ grep pattern file | awk '{ print } END { printf("Found %d matc
你好你好
你好你好
你好你好
你好你好
你好你好
b
dr
t
4
t
我希望能够打印出包含hello的n行,以及另外一行“找到了包含hello的n行”
我已经开始使用grep命令“grep hello.txt” 我知道“wc-l”查找输出有多少行。
我的想法是以某种方式使用sed工具进行管道连接,尽管我不太确定如何进行 使用awk,而不是sed:
$ grep pattern file | awk '{ print } END { printf("Found %d matching lines\n", NR) }'
您只需调用
grep
对包含“hello
”的行进行计算,然后第二次调用grep-c
,即可获得包含“hello”
的行数,例如
$ grep 'hello' file && grep -c 'hello' file
hello hello hello
hello hello hello
hello hello hello
hello hello hello
hello hello hello
5
$ grep 'hello' file && grep -c 'hello' file || echo '0'
通过在命令之间包括&&
,调用发生“hello”
次数的条件是文件中存在hello“
。如果要在未找到匹配项的情况下输出“0”
,则可以添加和| | echo“0”
,例如
$ grep 'hello' file && grep -c 'hello' file
hello hello hello
hello hello hello
hello hello hello
hello hello hello
hello hello hello
5
$ grep 'hello' file && grep -c 'hello' file || echo '0'
如果文件中不包含
“hello”
,则只输出“0”
。您可以使用awk编写一行程序
awk'/hello/'hello.txt | awk'{print}END{printf(“找到%d行有hello”),NR}'
grep'hello'文件;grep-c'hello'文件
或grep'hello'文件和&grep-c'hello'文件
。(第二种形式是在文件中成功找到“hello”
的条件下调用计数)请避免“给我密码”问题。而是显示您正在处理的脚本,并说明问题所在。也可以看到Downvoter,至少要诚实地解释你的Downvoter并留下评论。请随意指出答案中的任何技术错误(或上面的任何答案——因为看起来你只是为了满足一些深层次的不安全感或不充分感而进行了投票)。与其说是破坏性的,不如把你的答案贴出来——这样我们都可以知道应该怎么做。