Grep For Dev Null

A suggestion for UnixShellPatterns.

Motivation: You have a list of file names and want to run grep on them. You want the name of the file the match occurred in to appear in the output, possibly because grep's output will be used as input to another program. Grep will normally do that for you, except when there is only one file name in the list.

Solution: add /dev/null as one of the files to be grepped. That way, grep has two files to look through, even though it won't find much in /dev/null.

Typical uses:

1. The "grep" command in GNU emacs.

2. When using "xargs grep" -- there is always a threat that the last grep will get run with only one argument, even when there are lots of files, so one tends to use "xargs grep -flags /dev/null".

-- BillTrost, 8 June 1998

I HaveThisPattern. (When I've checked, it hasn't made a difference -- maybe xargs is smarter than I thought -- but it certainly can't hurt.) -- PaulChisholm

Some xargs implementations are smart enough to not invoke the command if there are no args for it, eg on AIX, others aren't, eg Solaris. Thank you for this pattern, I always though emacs' grep was just avoiding the perils of having the *grep* window hang forever because there were no inputs. I find this also works for certain kinds of tidyup which use xargs with rm, but run into trouble if there are no arguments - just so long as I don't run them as root, of course. find ...gunk... | xargs rm -f /dev/null

Now I HaveThisPattern ;^)

 -- EdwardWelbourne.

That's three, that's three! -- BT

NO! Its four or more! I HaveThisPattern since thrashing it out on comp.unix.questions in the nineteen-eighties -- DickBotting

I had this pattern, but I had no idea why until I read this. A colleague taught me this pattern for doing grep on a whole directory tree:

  find / -type f -exec grep 'Some String I'm Looking For' {} /dev/null \;

Until today, I never knew why the /dev/null was needed.


Incidentally, users of GNU Grep can use the -H / --with-filename option to force the filename to be displayed, even when there is only one. -- DanielBiddle


CategoryUnixShellPattern CategoryNull


EditText of this page (last edited August 28, 2007) or FindPage with title or text search