How to run find -exec?

  • I'd like to find the files in the current directory that contain the text "chrome".

    $ find . -exec grep chrome
    find: missing argument to `-exec'
    

    What am I doing wrong?

    I got `find: Only one instance of {} is supported with -exec ... +`

  • bmk

    bmk Correct answer

    10 years ago

    You missed a ; (escaped here as \; to prevent the shell from interpreting it) or a + and a {}:

    find . -exec grep chrome {} \;
    

    or

    find . -exec grep chrome {} +
    

    find will execute grep and will substitute {} with the filename(s) found. The difference between ; and + is that with ; a single grep command for each file is executed whereas with + as many files as possible are given as parameters to grep at once.

    If you use the \; ending construct grep is passed one file at a time, so it doesn't display the file name by default, only the matched lines. To get a file list instead add use `grep -ls` inside of the find construct.

    `find . -exec grep foo {} +` will show you output like this `./dir/file.py:from foo import bar`

    `find . -exec grep foo {} \;` will show you output like this `from foo import bar`

    `find . -exec grep -l foo {} +` will show you output like this `./dir/file.py`

    `find . -exec grep -l foo {} \;` will show you output like this `./dir/file.py`

    Or you could just `find . -print -exec grep chrome \;` to have `find` print out the file name...

    Similarly `find . -type f -execdir grep foo {} +` will show you output like this `./file.py:from foo import bar`

    @Caleb Or just add -H to the grep command to specifically include the file name in the result lists, giving the same formatting as grepping directly on multiple files: `file ./ -exec grep -H chrome {} \;`

    In `fish` shell you need to escape the braces too `find . -exec grep chrome \{\} \;`

    @Caleb If getting the list of files is the goal, I think one can do away with `find` and just use `grep`: `grep -ls 'chrome' *`

    @SvendHansen Do you mean `find` instead of `file`?

    Yes, indeed. Good spot, @flow2k :) (Unfortunately, I can't edit it now)

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM