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
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
Here's some ways:
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.
# 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
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 {} +
a[1] = "abc"
and a[2] = "bbc"
if (index($0, a[i]))