12

Consider the code to search for all files containing the pattern "search string":

bash-3.2$ # The below find works fine..
bash-3.2$ find . -type f -exec grep -il "search string" {} \;
bash-3.2$ # But I am unable to redirect output to a log file..
bash-3.2$ find . -type f -exec grep -il "search string" {} \ > log.txt
find: incomplete statement
bash-3.2$

From the man pages for Solaris find:

-exec command   True if the executed command returns a  zero
                value  as  exit  status.   The end of command
                must be punctuated by an  escaped  semicolon.
                A  command  argument  {}  is  replaced by the
                current path name.

So it seems an escaped semicolon is compulsory. Is there another way to go about this?

Anthon
  • 78,313
  • 42
  • 165
  • 222
Kent Pawar
  • 1,256
  • 4
  • 16
  • 37
  • A quick workaround would be to start [`script`](http://unixhelp.ed.ac.uk/CGI/man-cgi?script) before running the find command. – Hennes May 14 '13 at 10:49

1 Answers1

13

You're deleting the \;. Just do this:

find . -type f -exec grep -il "search string" {} \; > log.txt
terdon
  • 234,489
  • 66
  • 447
  • 667
  • Thanks! I finally understood it.. its escaped and `grep -il "search string" {} \;` is passed as an argument to the `find` command, so that's why the above works.. – Kent Pawar May 14 '13 at 11:06
  • @KentPawar well the `-exec` option of `find` will execute everything between `-exec` and `\;`. The `;` is escaped so it is not interpreted by the shell but passed to `find`. Mind you, you don't really _need_ the find, just do `grep -ril "search string" * > log.txt` to search through all files recursively. – terdon May 14 '13 at 11:09
  • 1
    okay. I had to go with find as the default grep on Solaris has no recursive capability. http://unix.stackexchange.com/questions/26483/recursive-search-doesnt-work-for-grep-on-solaris – Kent Pawar May 14 '13 at 11:28
  • 1
    @KentPawar If you have bash4+, you can just use `grep **/* "search string" > log.txt` with the `globstar` shell option. – Chris Down May 14 '13 at 11:41
  • thanks @ChrisDown, currently I am using GNU bash version 3.2.51 – Kent Pawar May 14 '13 at 13:30