Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a command which sends to stdout a series of numbers, each on a new line. I need to determine whether a particular number exists in the list. The match needs to be exact, not a subset. For example, a simple way to approach this that does not work would be to do:

/run/command/outputing/numbers | grep -c <numberToSearch>

My version of this gives a false positive on the following list when searching for '456':

1234567
98765
23
1771

If the count is non-zero, a match was found or if it was zero, the number is not in the list.

The issue with this is that the numberToSearch could match a subsequence of numbers on a line, instead I only want hits on the whole line. I looked at the man page for grep and did not see any way to only match whole lines. Is there a way to do this, or would I be better off using awk or sed or some other tool instead? I need a binary answer as to whether the number being search for is present or not.

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

Adding to Ansgar’s answer, consider -l (lower-case L) instead of -c.   It (-l) will give you a yes or no answer.

/run/command/outputting/numbers | grep –l '^456$'

will output “(standard input)” and exit with a status of 0 if a matching line is found; if the text is not found, it will output nothing and exit with a status of 1.  Some versions of grep also support a -q (quiet) option, which will suppress all output and give only the exit status.

These have the advantage that they are able to exit upon encountering the search string for the first time, and do not need to read the entire input.  If you need your command to run to completion, these options may be harmful.

share|improve this answer
add comment
num=23
/run/command/outputing/numbers | grep -c "^$num$"

Replace 23 with the number you're looking for.

share|improve this answer
    
If William is using the C shell, that would need to be something like "^$num"'$'. –  Scott Sep 12 '12 at 19:39
add comment

From the GNU grep manual:

`-x'
`--line-regexp'
     Select only those matches that exactly match the whole line.
     (`-x' is specified by POSIX.)

So:

/run/command/outputing/numbers | grep -x <numberToSearch>

Will get you the whole-line matches:

/run/command/outputing/numbers | grep -cx <numberToSearch> 

Will get you number of whole-line matches.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.