0

I would like to return only the first instance (case-insensitive) of the term I used to search (if there's a match), how would I do this?

example:

$ grep "exactly-this"

Binary file /Path/To/Some/Files/file.txt matches

I would like to return the result like:

$ grep "exactly-this"

exactly-this
T. Rex
  • 1

2 Answers2

0

grep has an inbuilt count argument

You can use the -m option to give a count argument to grep

grep -m 1 "exactly-this"

If you want to avoid the message in case of the binary files,use

grep -a -m 1 "exactly-this"

Note that this will print the word in which the match occurred.Since it is a binary file,the word may span over multiple lines

rjv
  • 6,058
  • 5
  • 27
  • 49
0

What you need is the -o option of grep.

From the man page

 -o, --only-matching
             Prints only the matching part of the lines.

Test:

[jaypal:~/Temp] cat file
This is a file with some exactly this in the middle
with exactly this in the begining
and some at the very end in brackets (exactly this)

[jaypal:~/Temp] grep -o 'exactly this' file
exactly this
exactly this
exactly this

[jaypal:~/Temp] grep -om1 'exactly this' file
exactly this
jaypal singh
  • 74,723
  • 23
  • 102
  • 147