Issue
I am searching a string using grep but the output displays unwanted files along with the correct file.
Ex:- xyz_utils.c Contains SAM22 keyword.
grep
command:
ret=$(grep -irwE "${excluded_files[@]/#/--exclude=}" "\\b${LIST[$A]}\\b|${LIST[$A]}[-_.*>@^:.,~%&\(\)\{}]|\\b${LIST[$A]}\\b" \
"$package/" |grep -v "$filters\|${excluded_dir[@]}" -c)
LIST[] -> Contains the list of words needs to be searched for.
Unwanted files displayed:
/home/sampath/SAM20_1.0.0/LICENSE.BSD: from this software without specific prior written permission.
/home/sampath/SAM20_1.0.0/LICENSE.BSD: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/home/sampath/SAM20_1.0.0/LICENSE.BSD: "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
/home/sampath/SAM20_1.0.0/LICENSE.BSD: LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
/home/sampath/SAM20_1.0.0/LICENSE.BSD: (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
/home/sampath/SAM20_1.0.0/LICENSE.BSD: OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.
.
/home/sampath/SAM20_1.0.0/README.txt: Static libraries included in SAM software package:
/home/sampath/SAM20_1.0.0/README.txt: Warning: This option should never be enabled in a production environment
.
.
Correct file displayed:
/home/sampath/SAM20_1.0.0/xyz_utils.c:SAM22
Solution
If I want to search for a string, like SAM22
, within a group of files, this is what I do:
find /<directory> -name "*.<extension>" -exec grep "SAM22" {} /dev/null \;
For your information: /dev/null
is a neat trick: as you might know, grep "entry" <filename>
shows entry
as a result (no filename), while grep "entry" <filename1> <filename2>
shows filename1:entry
, so by adding /dev/null
, I can force the output to show the filename too.
In case you say "I don't need the whole line, containing SAM22
, just the entry itself, this can be handled using the -o
switch:
find /<directory> -name "*.<extension>" -exec grep -o "SAM22" {} /dev/null \;
Answered By - Dominique Answer Checked By - David Marino (WPSolving Volunteer)