Your search is returning way more than you expected, including many results you don’t want.
Pipe the results into grep -v with an expression that describes what you don’t want to see.
Let’s say you were searching for messages in a log file, and you wanted all the messages from the month of December.
You know that your logfile uses the 3-letter abbreviation for December as Dec, but you’re not sure if it’s always written as Dec, so to be sure to catch them all you type:
1 |
$ grep -i dec logfile |
but you find that you also get phrases like these:
1 2 3 4 5 6 7 |
... error on Jan 01: not a decimal number error on Feb 13: base converted to Decimal warning on Mar 22: using only decimal numbers error on Dec 16 : the actual message you wanted error on Jan 01: not a decimal number ... |
A quick and dirty solution in this case is to pipe the first result into a second grep and tell the second grep to ignore any instances of “decimal”:
1 |
$ grep -i dec logfile | grep -vi decimal |
It’s not uncommon to string a few of these together (as new, unexpected matches are also discovered) to filter down the search results to what you’re really looking for:
1 |
$ grep -i dec logfile | grep -vi decimal | grep -vi decimate |
The “dirty” part of this “quick and dirty” solution is that the solution here might also get rid of some of the December log messages, ones that you wanted to keep—if they have the word “decimal” in them, they’ll be filtered out by the grep -v.
The -v option can be handy if used carefully; you just have to keep in mind what it might exclude.
For this particular example, a better solution would be to use a more powerful regular expression to match the December date, one that looked for “Dec” followed by a space and two digits:
But that often won’t work either because syslog uses a space to pad single digit dates, so we add a space in the first list [0-9 ]:
1 |
$ grep 'Dec [0-9 ][0-9]' logfile |
We used single quotes around the expression because of the embedded spaces, and to avoid any possible shell interpretation of the bracket characters (not that there would be, but just as a matter of habit).
It’s good to get into the habit of using single quotes around anything that might possibly be confusing to the shell.
We could have written:
1 |
$ grep Dec\ [0-9\ ][0-9] logfile |
escaping the space with a backslash, but in that form it’s harder to see where the search string ends and the filename begins.