Friday, November 12, 2021

[SOLVED] egrep add search pattern in result

Issue

I am searching multiple words in single search like below

egrep -rin 'abc|bbc' folder

I am want to get an output with search keyword in the result like

abc:folder/1.txt:32:abc is here
bbc:folder/ss/2.txt:2:    bbc is here

Solution

Here's some ways:

  1. Post process after all the results:
grep -rinE 'abc|bbc' folder | sed '/abc/{s/^/abc:/; b}; s/^/bbc:/'

If there are many search terms:

$ for p in abc bbc; do echo "/$p/{s/^/$p:/; b};" ; done > script.sed
$ cat script.sed
/abc/{s/^/abc:/; b};
/bbc/{s/^/bbc:/; b};

$ grep -rinE 'abc|bbc' folder | sed -f script.sed

Note that this solution and the next one both will need attention if contents of the search terms can conflict with sed metacharacters.

  1. Post process for each search term:
# add -F option for grep if search terms are fixed string
# quote search terms passed to the for loop if it can contain metacharacters
for p in abc bbc; do grep -rin "$p" folder | sed 's/^/'"$p"':/'; done
  1. With find+gawk
$ cat script.awk
BEGIN {
    OFS = ":"
    a[1] = @/abc/
    a[2] = @/bbc/
}

{
    for (i = 1; i <= 2; i++) {
        if ($0 ~ a[i]) {
            print a[i], FILENAME, FNR, $0
        }
    }
}

$ find folder -type f -exec awk -f script.awk {} +
  • If you are searching for fixed strings:
    • Change array to a[1] = "abc" and a[2] = "bbc"
    • Change the condition to if (index($0, a[i]))


Answered By - Sundeep