How to limit the number of results returned from grep?
Another advantage with this approach is that will return no more than 10 lines even if you are using grep with the -o option. Using head returns only 2 results as desired, whereas -m2 returns 3.
Do you need to use stdbuf to stop grep?
Note, that in order to ensure stopping after Nth match, you need to using stdbuf to make sure grep don’t buffer its output: As soon as head consumes 1 line, it terminated and grep will receive SIGPIPE because it still output something to pipe while head was gone.
When does grep exit after the first line?
head will exit as soon as it encounters the first line. grep will exit the next time it tries to write after head has exited. Some shells will wait until all elements of a pipeline finish, some will cause the entire pipe to shutdown as soon as the last program in the pipe exits.
What does grep only the first match mean?
-m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed. You can pipe grep result to head in conjunction with stdbuf.
How to show same number of lines before and after in grep?
If you want the same number of lines before and after you can use -C num. This will show 3 lines before and 3 lines after. -A and -B will work, as will -C n (for n lines of context), or just -n (for n lines of context… as long as n is 1 to 9).
How to limit grep context to n characters?
Any tool other than grep would be fine as well, so long as it available in common Linux packages. N=10; grep -roP “. {0,$N}foo. {0,$N}” . The regex says match 0 to $N characters followed by foo followed by 0 to $N characters.
Which is faster to search code AG or grep?
If you search code often, AG the silver searcher is much more efficient (ie faster) than grep. You show context lines by using -C option. You can use option -A (after) and -B (before) in your grep command. Try grep -nri -A 5 -B 5 .