简体   繁体   中英

How to display the first line that contains a certain string in a text file unix?

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 ie "computer" (first occurrence of "computer" in a txt file). I would prefer to do this using grep.

I know 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

Use the match count option of 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 "computer" somefile.txt | head -n1

Is this homework?

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

Comes to mind the quickest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM