bash 如何在unix中打印出包含特定字符串的文件的所有行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15650506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:00:12  来源:igfitidea点击:

How can I print out all lines of a file containing a specific String in unix

bashunix

提问by user2012751

I know how to print out the line of the first occurrence of the String but I'm not sure how to print out all occurrences. To print out the first occurrence of my String I have used

我知道如何打印出字符串第一次出现的行,但我不确定如何打印出所有出现的行。打印出我使用的字符串的第一次出现

grep ",1," my_course.

I feel like printing out all occurrences would look something like:

我觉得打印出所有事件看起来像:

    while(file has next line)
         grep ",1," my_course

I'm not sure how to do this while loop though. How do I test if file has next line.

不过,我不确定如何在 while 循环中执行此操作。如何测试文件是否有下一行。

EDIT: Sorry guys I thought grep only matched the first occurrence. When I ran it, it only matched 1 line. I didn't know only 1 line matched

编辑:对不起,我认为 grep 只匹配第一次出现。当我运行它时,它只匹配了 1 行。我不知道只有 1 行匹配

Also, bonus question if someone wants to answer... if all the lines in my file (my_course) look like "number,name,credit hours,grade" how would I get all the grades in the file and store into an array?

另外,如果有人想回答的话,奖金问题......如果我的文件(my_course)中的所有行看起来像“数字,名称,学分,等级”,我将如何获取文件中的所有等级并将其存储到数组中?

回答by ktm5124

grepalready prints out all occurrences.

grep已经打印出所有事件。

From the man pagesof grep:

从grep的手册页

grep, egrep, fgrep - print linesmatching a pattern

的grep,egrep的,fgrep一样-印刷线的图案匹配