Problem
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 understand the command I want to use and how to grep out the required string(s).
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.
Asked by user2147075
Solution #1
It would suffice to use grep $PATTERN *. All subdirectories are skipped by default when using grep. grep -r $PATTERN * is the case if you want to grep through them.
Answered by umi
Solution #2
I usually use this command on Linux to recursively grep for a specific text within a directory:
grep -rni "string" *
where
Answered by Narain
Solution #3
Make use of the find function. Seriously, it’s the greatest method because you can see exactly which files it’s working on:
find . -name "*.sql" -exec grep -H "slow" {} \;
Note that the -H specifies a Mac and displays the filename in the results.
Answered by Rob
Solution #4
To search in all sub-directories, but only in specific file types, use grep with –include.
Searching recursively in the current directory for text in *.yml and *.yaml, for example:
grep "text to search" -r . --include=*.{yml,yaml}
Answered by Noam Manos
Solution #5
If you want to run a series of commands, type:
for I in `ls *.sql`
do
grep "foo" $I >> foo.log
grep "bar" $I >> bar.log
done
Answered by bryan
Post is based on https://stackoverflow.com/questions/15286947/how-to-perform-grep-operation-on-all-files-in-a-directory