How to perform grep operation on all files in a directory?

LinuxShellGrep

Linux Problem Overview


Working with xenserver, and I want to perform a command on each file that is in a directory, grepping some stuff out of the output of the command and appending it in a file.

I'm clear on the command I want to use and how to grep out string(s) as needed.

But what I'm not clear on is how do I have it perform this command on each file, going to the next, until no more files are found.

Linux Solutions


Solution 1 - Linux

grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

Solution 2 - Linux

In Linux, I normally use this command to recursively grep for a particular text within a directory:

grep -rni "string" *

where

  • r = recursive i.e, search subdirectories within the current directory
  • n = to print the line numbers to stdout
  • i = case insensitive search

Solution 3 - Linux

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

Solution 4 - Linux

To search in all sub-directories, but only in specific file types, use grep with --include.

For example, searching recursively in current directory, for text in *.yml and *.yaml :

grep "text to search" -r . --include=*.{yml,yaml}

Solution 5 - Linux

If you want to do multiple commands, you could use:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2147075View Question on Stackoverflow
Solution 1 - LinuxumiView Answer on Stackoverflow
Solution 2 - LinuxNarainView Answer on Stackoverflow
Solution 3 - LinuxRobView Answer on Stackoverflow
Solution 4 - LinuxNoam ManosView Answer on Stackoverflow
Solution 5 - LinuxbryanView Answer on Stackoverflow