匹配所有出现在与grep - Match all occurrences in a line with grep

- 此内容更新于:2015-12-20
主题:

你怎么能匹配所有字符,直到第一次出现一个特定的字符序列?我寻找一种方法来完成这项任务在Linux环境中,因为我可能缺少一些关键的grep功能,红外的创意解决方案也欢迎。问题还包括分别匹配一行中出现的所有模式。更好地了解有关情况,假设有一个命令看起来比赛直到最后出现的序列,所以当我们运行这个:我真正寻找的是:

原文:

How could you match all characters until first occurrence of a particular sequence of characters with grep? I'm looking for a way to accomplish this task in Linux environment and since I might missing some crucial point of grep functionality, ideas with solutions with awk ir sed are also welcome.

The problem also involves matching separately all occurrences of the pattern in a single line.

To better understand the situation, let's say we have a command
echo "word word" | grep -o 'w.*rd'

It looks like it matches up until last occurrence of the sequence rd, so when we run this we get:
word word

What I'm actually looking for is:

word
word
解决方案:
你需要做非贪婪匹配,停止在第一次出现。但由于不支持非贪婪匹配在默认情况下,您可以使用否定字符类:如果你GNUgrep,然后您可以使用选项来启用Perl的正则表达式语法。然后这将工作:
原文:

You need to do non-greedy match here, to stop at first occurrence. But since grep doesn't support non-greedy match by default, you can use negated character class:

echo "word word" | grep -o 'w[^r]*rd'

If you've GNU grep, then you can use -P option to enable Perl regex syntax. And then this would work:

echo "word word" | grep -Po 'w.*?rd'
解决方案:
可以使用选项扩展正则表达式和使用(非贪婪匹配):
原文:

You can use -E option in grep for extended regex and use .*? (non-greedy match):

echo "word word" | grep -Eo 'w.*?rd'
word
word
解决方案:
“grep”返回指定的模式匹配的每一行。似乎你正在寻找匹配模式的每个单词,而不是每一行。如何打破单个词的输入行吗?像这样的,例如:
原文:

"grep" returns every row that matched against the pattern you specified.

It seems that you're looking for matching the pattern per word and not per row.

How about breaking the input into rows of single words? Like this, for example:

echo "word word" | tr -s ' '  '\n' | grep word