简体   繁体   中英

Find every occurrence of a regex in a file

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 time. 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]'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM