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
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.
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.
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.
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.
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.
Pipes are your friend:
grep "computer" somefile.txt | head -n1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With