bash 如何从正则表达式中获取所有匹配项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/642067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:45:35  来源:igfitidea点击:

How to get all matches from regex?

regexbashshell

提问by michal kralik

I would like to get all occurrences of [0-9A-Z]+?for processing later. I do have

我想得到所有出现的[0-9A-Z]+?以供稍后处理。我有

if [[ `cat file` =~ '[0-9A-Z]+?' ]]; then
  echo $BASH_REMATCH;
fi

Which gives me first match, but how could I process all the matches in the file?

这给了我第一场比赛,但我如何处理文件中的所有比赛?

Thank you

谢谢

采纳答案by Ian Kelling

If you want to get just the matched text of a regular expression, I would use

如果您只想获取正则表达式的匹配文本,我会使用

grep -o 'regex' file

In the spirit of your code I would modify it to be

本着您的代码精神,我会将其修改为

while read line; do
    [[ $line =~ regex ]] || continue
    # do somethinw with $line or $BASH_REMATCH, perhaps put it in an array.
done < file

If you want to match multiple regexes on the same line, here is a way.

如果你想在同一行匹配多个正则表达式,这里有一个方法。

while read line; do
    # do somethinw with $line
done < <(grep -o 'regex' file)

I assume your regex is supposed to be a simplified example of what your really doing. The ? is not helpfull and your quotes are matching a literal string.

我认为您的正则表达式应该是您真正在做什么的简化示例。这 ?没有帮助,并且您的引号与文字字符串匹配。