如何在文本文件unix中显示包含特定字符串的第一行?

时间:2022-09-20 22:26:59

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

大家好

3 个解决方案

#1


17  

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.

请注意,grep在un * x中是非标准的,所以虽然http://www.gnu.org/software/grep/支持这一点,但如果你的发行版或unix不支持,那么这将不起作用。

#2


10  

Pipes are your friend:

管道是你的朋友:

grep "computer" somefile.txt | head -n1

#3


-1  

Is this homework?

这是家庭作业吗?

grep -v "computer" somefile.txt | head -n 1

Comes to mind the quickest.

想到最快的。

#1


17  

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.

请注意,grep在un * x中是非标准的,所以虽然http://www.gnu.org/software/grep/支持这一点,但如果你的发行版或unix不支持,那么这将不起作用。

#2


10  

Pipes are your friend:

管道是你的朋友:

grep "computer" somefile.txt | head -n1

#3


-1  

Is this homework?

这是家庭作业吗?

grep -v "computer" somefile.txt | head -n 1

Comes to mind the quickest.

想到最快的。