grep on Windows 7 Invalid Argument

1

I am using grep from Gnuwin32 on Windows.

Doing:

grep -r INSERT *.sql

Yields:

grep: *.sql: Invalid argument

Any idea why?

Mike

Posted 2015-10-23T14:29:38.300

Reputation: 113

Have you updated gnuwin32? Command appears to work correctly for me. There was an older bug that had this behavior. – monkey – 2015-10-23T14:40:40.197

Answers

2

According to the Grep manual:

-r with grep is recursive directory searching, so to use it you specify the starting directory, not a file mask.

e.g.:

grep -r INSERT . would look at all files for INSERT, starting at the current directory (.) and recursively working its way through the sub-folders.

To specify recursive folder checking and specify a file wildcard to limit searches, you can use the --include option:

grep -r --include "*.sql" INSERT .

Similar question/info over on StackOverflow: How do I grep recursively?

Ƭᴇcʜιᴇ007

Posted 2015-10-23T14:29:38.300

Reputation: 103 763

I think I need to update my grep. I have no --include option! But this makes a lot of sense. – Mike – 2015-10-26T16:54:11.810

2

Because there is no *.sql file.

jan.supol

Posted 2015-10-23T14:29:38.300

Reputation: 231

While that in fact is true, adding -r yields the same error. – Mike – 2015-10-23T15:45:33.483

@Mike bash expands *.sql to all files/ directories matching this pattern. Since nothing matches, you get the error. -r doesn't have anything to do with this – fedorqui – 2015-10-23T15:48:35.133

Sorry, I don't follow. There are no files with an extension of .sql in the folder where I ran the command. There are subfolders and they do in fact have files with .sql as the extension. Shouldn't the -r help then? – Mike – 2015-10-23T15:56:52.433

TECHIE007 has a nice answer to this. Completely unrelated to your question, perhaps for fun, or for comparison, I'd like just to add the non-Gnuwin32 solution that likely does the same thing: @for /f %i in ('dir /s/b *.sql') do @(type %i | find "INSERT" > nul && if errorlevel 0 echo %i). – jan.supol – 2015-10-23T17:09:42.133

1

grep is a great tool with some interesting parameters. However, as its name says (globally search a regular expression and print) it is meant for matching things. If what you want is to find files, use find.

In this case, it looks like you want to look for the text INSERT within files that are in this tree.

For this, you need to do something like:

find -name "*.sql" grep -h INSERT {} \;

find -name "*.sql" will find all these files and then grep -h will print those having the text INSERT in them.


Why wasn't your approach working?

Because by saying grep -r ... *.sql, bash tries to expand that *.sql before performing the command. But nothing matches *.sql in your directory, so it cannot work.

You can use the --include parameter with a regexp, but -in my experience- it is quite fragile.

fedorqui

Posted 2015-10-23T14:29:38.300

Reputation: 1 517