从命令行打印正则表达式的所有匹配项?
在 unix 命令行上将所有匹配项(每个匹配项一行或每行输入一行)打印到正则表达式的最简单方法是什么?请注意,每行输入可能有 0 个或超过 1 个匹配项。
我认为必须有某种方法可以使用 sed、awk、grep 和/或 perl 来完成此操作,并且我希望有一个简单的命令行解决方案,以便将来需要时它会显示在我的 bash 历史记录中。
编辑:为了澄清,我不想打印所有匹配的行,只想打印正则表达式的匹配项。例如,一行可能有 1000 个字符,但只有两个 10 个字符与正则表达式匹配。我只对那两个 10 个字符的比赛感兴趣。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您仅使用非捕获括号,
或
示例使用:
Assuming you only use non-capturing parentheses,
or
Sample use:
除非我误解了你的问题,否则以下内容将解决问题
有关更多详细信息,请参阅:
Unless I misunderstand your question, the following will do the trick
For more details see:
离开注释,假设您从管道或其他方式在
STDIN
上传递了输入:用法:
或者我只是将整个乱七八糟的东西塞进 bash 函数...
用法是相同的,只是看起来更干净:(
或者只需键入命令本身并输入文本以逐行匹配,但这似乎不是一个可能的用例:)。
示例(来自您的评论):
或...
Going off the comment, and assuming you're passed the input from a pipe or otherwise on
STDIN
:Usage:
or I would just stuff that whole mess into a bash function...
Usage is the same, just cleaner-looking:
(or just type the command itself and enter the text to match line-by-line, but that didn't seem a likely use case :).
Example (from your comment):
or...