Linux 如何在文本文件unix中显示包含某个字符串的第一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12683826/
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
How to display the first line that contains a certain string in a text file unix?
提问by Masterminder
Was hoping someone can help out with this. I am trying to figure out how to display the first line that contains a certain string i.e. "computer" (first occurrence of "computer" in a txt file). I would prefer to do this using grep.
希望有人可以帮助解决这个问题。我想弄清楚如何显示包含某个字符串的第一行,即“计算机”(txt 文件中第一次出现“计算机”)。我更愿意使用 grep 来做到这一点。
I know grep "computer" somefile.txt
我知道 grep "computer" somefile.txt
would display all of the lines including "computer". I am eager to learn and if anyone has alternative ways I would like to hear!
将显示所有行,包括“计算机”。我渴望学习,如果有人有其他方法,我想听听!
Thx everyone
谢谢大家
采纳答案by Adrian Cornish
Use the match count option of grep
使用 grep 的匹配计数选项
grep -m 1 "computer" somefile.txt
Note that grep is non standard across un*x's so while http://www.gnu.org/software/grep/supports this, if your distro or unix does not this will not work.
请注意,在 un*x 中 grep 是非标准的,因此虽然http://www.gnu.org/software/grep/支持这一点,但如果您的发行版或 unix 不支持,这将不起作用。
回答by Sandro
Is this homework?
这是家庭作业吗?
grep -v "computer" somefile.txt | head -n 1
Comes to mind the quickest.
想到的最快。
回答by singpolyma
Pipes are your friend:
管道是你的朋友:
grep "computer" somefile.txt | head -n1