Reputation: 53
I want to grep for a string in all the files which have a particular patter in their name and is case-insensitive.
For eg if I have two files ABC.txt and aBc.txt, then I want something like
grep -i 'test' *ABC*
The above command should look in both the files.
Upvotes: 2
Views: 1459
Reputation: 6372
You can use find
and then grep
on the results of that:
find . -iname "*ABC*" -exec grep -i "test" {} \;
Note that this will run grep
once on each file found. If you want to run grep
once on all the files (in which case you risk running into the command line length limit), you can use a plus at the end:
find . -iname "*ABC*" -exec grep -i "test" {} \+
You can also use xargs
to process a really large number of results more efficiently:
find . -iname "*ABC*" -print0 | xargs -0 grep -i test
The -print0
makes find
output 0-terminated results, and the -0
makes xargs
able to deal with this format, which means you don't need to worry about any special characters in the filenames. However, it is not totally portable, since it's a GNU extension.
If you don't have a find
that supports -print0
(for example SVR4), you can still use -exec
as above or just
find . -iname "*ABC*" | xargs grep -i test
But you should be sure your filenames don't have newlines in them, otherwise xargs
will treat each line of a filename as a new argument.
Upvotes: 1
Reputation: 19
You should use find
to match file and search string that you want with command grep
which support regular expression, for your question, you should input command like below:
find . -name "*ABC*" -exec grep \<test\> {} \;
Upvotes: 0