开发者

Find every occurrence of a regex in a file

开发者 https://www.devze.com 2023-04-08 12:33 出处:网络
How can I list every occurrence of a regex in a file, where one line can contain the regex multiple times?

How can I list every occurrence of a regex in a file, where one line can contain the regex multiple times?

Example:
XXXXXXXXXX FOO3 XXXX FOO4 XXX
XXX FOO2 XXXX FOO9 XXXXXX FOO5

The result should be:
FOO3
FOO4
FOO2
FOO9
FOO5

The regex would be /FOO./ in this case.

Grep will return every line that matches at least one t开发者_运维知识库ime. But that's not what I want.


Have you tried the -o option: (grep man page)

-o, --only-matching Show only the part of a matching line that matches PATTERN.


You question is not completely clear, especially since the example data is super generic. But, here are some patterns that might match:

Your pattern matches FOO followed by any character which would match everything to the end of the line. I don't think you want that so try something like this:

/FOO[0-9]+/ - matches FOO followed by one or more numbers.

/FOO[^ ]+/ - matches FOO followed by any character that is NOT a space. This might be the best solution given your example pattern.

/FOO[0-9a-zA-Z]+/ - matches FOO followed by any alphanumeric character


Use grep -o FOO. (-o: show only matching)

Your regex could even be extended to only match FOO followed by a number, instead of any character (. will match whitespace too!):

<yourfile grep -o 'FOO[0-9]'
0

精彩评论

暂无评论...
验证码 换一张
取 消