Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

grep

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 i.e. "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

like image 812
Masterminder Avatar asked Oct 02 '12 02:10

Masterminder


People also ask

How do you display the first line of a text file in Unix?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.

How do I display a specific line in a file in Unix?

Using the head and tail Commands Let's say we want to read line X. The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.

How do I print a line containing a string in Linux?

To print the lines of a file that contain a specific string or text, we use linux grep command. Here we are giving the input to the command like which file you want to search. it will search in that file for that particular string or text and it will print the lines with line numbers.

How do I find a specific string in Unix?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.


2 Answers

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.

like image 61
Adrian Cornish Avatar answered Oct 14 '22 01:10

Adrian Cornish


Pipes are your friend:

grep "computer" somefile.txt | head -n1
like image 45
singpolyma Avatar answered Oct 14 '22 01:10

singpolyma