egrep 在结果中添加搜索模式
egrep add search pattern in result
我在单次搜索中搜索多个单词,如下所示
egrep -rin 'abc|bbc' folder
我想在结果中获得带有搜索关键字的输出,例如
abc:folder/1.txt:32:abc is here
bbc:folder/ss/2.txt:2: bbc is here
这里有一些方法:
- Post 处理完所有结果:
grep -rinE 'abc|bbc' folder | sed '/abc/{s/^/abc:/; b}; s/^/bbc:/'
如果有很多搜索词:
$ 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
注意 如果搜索词的内容可能与 sed
个元字符冲突,则此解决方案和下一个解决方案都需要注意。
- Post 每个搜索词的处理:
# 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 ([=13=] ~ a[i]) {
print a[i], FILENAME, FNR, [=13=]
}
}
}
$ find folder -type f -exec awk -f script.awk {} +
- 如果您要搜索固定字符串:
- 将数组更改为
a[1] = "abc"
和 a[2] = "bbc"
- 将条件更改为
if (index([=18=], a[i]))
我在单次搜索中搜索多个单词,如下所示
egrep -rin 'abc|bbc' folder
我想在结果中获得带有搜索关键字的输出,例如
abc:folder/1.txt:32:abc is here
bbc:folder/ss/2.txt:2: bbc is here
这里有一些方法:
- Post 处理完所有结果:
grep -rinE 'abc|bbc' folder | sed '/abc/{s/^/abc:/; b}; s/^/bbc:/'
如果有很多搜索词:
$ 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
注意 如果搜索词的内容可能与 sed
个元字符冲突,则此解决方案和下一个解决方案都需要注意。
- Post 每个搜索词的处理:
# 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 ([=13=] ~ a[i]) {
print a[i], FILENAME, FNR, [=13=]
}
}
}
$ find folder -type f -exec awk -f script.awk {} +
- 如果您要搜索固定字符串:
- 将数组更改为
a[1] = "abc"
和a[2] = "bbc"
- 将条件更改为
if (index([=18=], a[i]))
- 将数组更改为