I have a directory structure based on events.
In these events, I have one type of file which does or does not contain a pattern for which I need to search. The positive results I would like to store in a separate file.
My first approach was:
find . /EVENT*/'filename' | grep 'searchtext' head -2 > error_file
but that does not seem to work. I was told that it is not possible to combine find
and grep
in this way, so how do I need to do it?
Best Answer
Here is a general pattern:
Here at first
find
will search all files in the directory containing necessary files, you can also use wildcards e.g.*.txt
to look for only files ending with.txt
. In that case the command would be:After finding the necessary files we are searching for the desired pattern in those files using
-exec grep -H 'pattern_to_search' {} +
(-H
will print the filename where the pattern is found). Here you can think of{}
as containing the files to be searched and+
is needed to be used at the end with-exec
so that-exec
will be forked only once i.e.grep
will search as if the command isgrep -H 'pattern_to_search' file_1.txt file_2.txt file_3.txt
.