我想用包含正则表达式的文件中的模式进行 grep。 当模式匹配时,它打印匹配的字符串而不是模式。 如何获取模式而不是匹配的字符串?
图案.txt
Apple (Ball|chocolate|fall) Donut
donut (apple|ball) Chocolate
Donut Gorilla Chocolate
Chocolate (English|Fall) apple gorilla
gorilla chocolate (apple|ball)
(ball|donut) apple
字符串.txt
apple ball Donut
donut ball chocolate
donut Ball Chocolate
apple donut
chocolate ball Apple
这是grep命令
grep -Eix -f pattern.txt strings.txt
此命令从 strings.txt 打印匹配的字符串
apple ball Donut
donut ball chocolate
donut Ball Chocolate
但我想从 pattern.txt 中找到哪些模式被用来匹配
Apple (Ball|chocolate|fall) Donut
donut (apple|ball) Chocolate
pattern.txt 可以是小写字母、大写字母、带正则表达式和不带正则表达式的行、自由数量的单词和正则表达式元素。除了方括号和竖线,没有其他类型的正则表达式。
我不想使用循环将 pattern.txt 的每一行读取到 grep,因为它很慢。 有没有办法在 grep 命令中打印模式文件的模式或行号?或者除 grep 之外的任何其他命令都可以完成这项工作而不是太慢?
最佳答案
使用 grep
我不知道,但使用 GNU awk:
$ awk '
BEGIN { IGNORECASE = 1 } # for case insensitivity
NR==FNR { # process pattern file
a[$0] # hash the entries to a
next # process next line
}
{ # process strings file
for(i in a) # loop all pattern file entries
if($0 ~ "^" i "$") { # if there is a match (see comments)
print i # output the matching pattern file entry
# delete a[i] # uncomment to delete matched patterns from a
# next # uncomment to end searching after first match
}
}' pattern strings
输出:
D (A|B) C
对于 strings
中的每一行,脚本将循环每个 pattern
行以查看是否有多个匹配项。由于区分大小写,只有一个匹配项。您可以解决这个问题,例如,使用 GNU awk 的 IGNORECASE
.
此外,如果您希望每个匹配的模式文件条目都输出一次,您可以在第一次匹配后从 a
中删除它们:在之后添加 delete a[i]
打印
。这也可能会给您带来一些性能优势。
关于bash - 从文件中获取模式,打印模式而不是匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51822216/