0

If I have two lines of text:

HOOK
HOOK HOOK

what is the syntax to grep just the first line without the second? and the second without the first?

4
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by Xydric
3

If I have two lines of text:

HOOK
HOOK HOOK

what is the syntax to grep just the first line without the second? and the second without the first?

Find any difference between both and then match it. e.g. with HOOK by itself in a line we can match the beginning and end of the line. Thus:

grep '^HOOK$' file_name

Once you have down the successful match the opposite will work in this case, using the -v switch.

grep -v '^HOOK$' file_name

Will match HOOK HOOK
However, if there were another line containing something that is not ^HOOK$ it will produce a match as well.

0

Are you wanting to try and grep "HOOK" on a line by itself, or specifically just the first match?

There are all sorts of things that you could actually want to know, although I am not sure which you are wanting. What exactly is it that you are needing to do?

# grep a file, return first result and stop
grep -m1 "HOOK" file.txt

# grep a file, only return result with HOOK on line by itself
grep -P "^HOOK$" file.txt
# you can also use egrep (or instead of -P use pgrep)
0

Aia - You beat me to it! Well, if the original poster wants to limit the number of matches, then -m1 would work

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.