Ubuntu: Grep showing file name and string found



Question:

I need an egrep command that list all the file names that contains the words + which string it has found. Let's imagine this scenario:

Words that I need to find: apple, watermelon and banana.

What I need: I want to list all files that contains any of them (don't need to have all of them in the same file), and print which word it found in the file. Example of a search result I want:

./file1.txt:apple  ./file1.txt:banana  ./file2.txt:watermelon  ./file5.txt:apple  

I remember seeing a grep command which shows FILENAME:STRING in the search results, but I can't remember how it was done. I tried:

egrep -lr 'apple|banana|watermelon' .  

But the search results showed:

./file1.txt  ./file2.txt  

Ok, it helps but ... in file1, which one of the words it found? That's the problem I'm facing .


Solution:1

The way to do it with awk:

awk -v var1=apple -v var2=banana -v var3=watermelon '{ if($0~var1) {print FILENAME":"var1} ; if($0~var2) {print FILENAME":"var2} ; if($0~var3) {print FILENAME":"var3}  }' *  

Basically, declare 3 variables, and 3 if statements to print filename and corresponding variable that has been found

EDIT

Shorter version:

awk '/watermelon/{ print FILENAME":watermelon" }; /banana/{print FILENAME":banana"}; /apple/ {print FILENAME":apple"}' *

Basic idea find /regular expression/ and execute code in curly braces after it if found (which is to print FILENAME and which string we found ).


Solution:2

You used -l, which is the opposite of what you want. From man grep:

-l, --files-with-matches        Suppress normal output; instead print the  name  of  each  input        file  from  which  output would normally have been printed.  The        scanning will stop on the first  match.   (-l  is  specified  by        POSIX.)  

What you want is -H:

-H, --with-filename        Print the file name for each match.  This is  the  default  when        there is more than one file to search.  

But that's the default anyway. Just do:

grep -Er 'apple|banana|watermelon' .  

(The -E tells grep to act like egrep.)


Solution:3

Here is the command you're looking for:

grep -R "apple\|banana\|watermelon" <search_path>  

The -R will read all files under each directory in search_path, recursively. The file name will be displayed for each match.


Solution:4

The following will give you the output you want (using bash):

for x in apple banana watermelon ; do grep $x * ; done  

The output will give you all lines containing the search string.

The following will give you only the search string as output:

for x in apple banana watermelon ; do grep -l $x * |xargs -I{} echo {}:$x; done  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »