从命令行打印正则表达式的所有匹配项? [英] Print all matches of a regular expression from the command line?
问题描述
在unix命令行中将所有匹配(每个匹配一行或每行输入一行)打印到正则表达式的最简单方法是什么?请注意,每行输入可能有0个或多个匹配。
我认为必须有一些方法可以通过sed,awk,grep和/或perl,我希望有一个简单的命令行解决方案,以便在未来需要时显示在我的bash历史记录中。
编辑:澄清,我不想打印所有匹配的行,只打印正则表达式的匹配项。例如,一行可能有1000个字符,但与正则表达式只有两个10个字符的匹配。我只对这两个10个字符的匹配感兴趣。假设您只使用非捕获括号,
perl -wnE'say / yourregex / g'
或
perl -wnE'say for / yourregex / g'
示例使用:
$ echo -ne'fod,food,fad\\\
bar\\\
fooooood\\\
'| perl -wnE'say for / fo * d / g'
fod
food
fooooood
$ echo -ne'fod,food,fad\\\
bar\\\
fooooood\ n'| perl -wnE'say / fo * d / g'
fodfood
fooooood
What's the simplest way to print all matches (either one line per match or one line per line of input) to a regular expression on a unix command line? Note that there may be 0 or more than 1 match per line of input.
I assume there must be some way to do this with sed, awk, grep, and/or perl, and I'm hoping for a simple command line solution so it will show up in my bash history when needed in the future.
EDIT: To clarify, I do not want to print all matching lines, only the matches to the regular expression. For example, a line might have 1000 characters, but there are only two 10-character matches to the regular expression. I'm only interested in those two 10-character matches.
Assuming you only use non-capturing parentheses,
perl -wnE'say /yourregex/g'
or
perl -wnE'say for /yourregex/g'
Sample use:
$ echo -ne 'fod,food,fad\nbar\nfooooood\n' | perl -wnE'say for /fo*d/g'
fod
food
fooooood
$ echo -ne 'fod,food,fad\nbar\nfooooood\n' | perl -wnE'say /fo*d/g'
fodfood
fooooood
这篇关于从命令行打印正则表达式的所有匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!