Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex Linux工具-如何计算和列出文件中正则表达式的出现次数_Regex_Linux - Fatal编程技术网

Regex Linux工具-如何计算和列出文件中正则表达式的出现次数

Regex Linux工具-如何计算和列出文件中正则表达式的出现次数,regex,linux,Regex,Linux,我有一个包含大量类似字符串的文件。我想计算正则表达式的唯一出现次数,并显示它们是什么,例如,对于文件上的模式配置文件:(\w*): Profile: blah Profile: another Profile: trees Profile: blah 我希望找到3个实例,并返回结果: blah, another, trees 试试这个: egrep "Profile: (\w*)" test.text -o | sed 's/Profile: \(\w*\)/\1/g' | sort | u

我有一个包含大量类似字符串的文件。我想计算正则表达式的唯一出现次数,并显示它们是什么,例如,对于文件上的模式
配置文件:(\w*)

Profile: blah
Profile: another
Profile: trees
Profile: blah
我希望找到3个实例,并返回结果:

blah, another, trees
试试这个:

egrep "Profile: (\w*)" test.text -o | sed 's/Profile: \(\w*\)/\1/g' | sort | uniq
输出:

another
blah
trees
3
说明

带有
-o
选项的
egrep
将获取文件中的匹配模式

sed
将仅获取捕获部分

sort
后跟
uniq
将给出唯一元素的列表

要获取结果列表中的元素数,请在命令后面附加
wc-l

egrep "Profile: (\w*)" test.text -o | sed 's/Profile: \(\w*\)/\1/g' | sort | uniq | wc -l
输出:

another
blah
trees
3
我会用你的例子

kent$  echo "Profile: blah
Profile: another
Profile: trees
Profile: blah"|awk '{a[$2]}END{for(x in a)print x}'
another
trees
blah
如果要在输出中获得计数(3):

awk '{a[$2]}END{print "count:",length(a);for(x in a)print x }' file
举同样的例子:

kent$  echo "Profile: blah
Profile: another
Profile: trees
Profile: blah"|awk '{a[$2]}END{print "count:",length(a);for(x in a)print x }'
count: 3
another
trees
blah

+1要返回正确的列表,只需半个答案,因为它不返回计数。此解决方案有效。。就个人而言,我不喜欢将
grep | sed | sort | uniq
四个过程结合起来。。。如果OP想要清点人数,我想,
wc
可以参加派对吗?@Stefan谢谢你的指点。我只是更新了一篇文章的描述和内容extension@Kent我想知道简明的解决方案。但就我个人而言,我喜欢简洁易读,而不是记住单一选项的复杂组合utility@Kent我完全同意你的看法。我曾经遇到过处理大型文件的开销问题。但我也是一个初学者,渴望知道最佳解决方案。我知道您已经使用了
awk
,并将尝试理解它。+1用于考虑效率。虽然我同意你的答案更简洁,也可能更有效,但实际上解析jkshah的答案更容易理解在哪里用我想要的变量替换他的变量,例如正则表达式字符串。@Kent如果添加
Nomatch:Nomatch
,这将失败,并产生错误的传递。这里OP需要只匹配
配置文件的行:(\w*)
@Kent这是否使用任何正则表达式?我完全不熟悉
awk
@jkshah也许你是对的。应检查模式。这将是非常容易添加到一个班轮。根据所讨论的示例数据,我们不需要regexp。@Kent Aha!基于这个示例数据的假设,我本可以删除
grep
then;)<代码>sed | sort | uniq只会work@Stefen我假设
NoMatch:NoMatch
行不应该出现在结果中。请确认。如果是这样,请在示例中也添加这样的负字符串,这样您就不会得到错误的通过