Using grep or sed to return a regex match
Hi folks,
I'm working on a script that I want to search through a file for a regex match, and store each different match in an array. For instance, if I have a regex to search for an IP address, I would want to store each unique IP address found in the script to the array. For this reason, I'm trying to find a way that, presumably with grep (or sed?), I can return the match found rather than the full line of text the line was found in. Is this possible? I could strip the match from the line matched, but this would lead to extra complication with multiple matches on a single line. Am I missing something obvious? Thanks in advance... |
Check whether your implementation of grep supports the "-o" flag.
|
Quote:
svr:user$ grep -o hello email.txt grep: illegal option -- o usage: grep [-[[AB] ]<num>] [-[CEFGVchilnqsvwx]] [-[ef]] <expr> [<files...>] |
Using sed:
Code:
array=( $(sed 's/[^0-9]*\([0-9]\+\.[0-9]\+\.[0-9]\+.[0-9]\+\).*/\1/' file | uniq) ) |
Hi,
try this: Code:
sed -nr "s/.*(PATTERN_TO_MATCH).*/\1/p" file 1.2.3.4 must become 1\.2\.3\.4 |
@crts: good catch for the -n /p option. Regarding the -r option, it's not available on Solaris' sed (if I remember well), so that we have to escape parentheses to let them work as intended. The only thing I cannot solve using this sed approach is the presence of multiple IP addresses on the same line (if any).
|
Quote:
Code:
some junk 1.2.3.4 some more junk with numbers 2.3.4.5 eol Code:
sed -rn 's/[^0-9]*(([0-9]+\.){3}[0-9]+)/\1\n/;T;P;D' file Code:
sed --posix -n 's/[^0-9]*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)/\1\n/;t a;b;:a P;D' file So we finally get something like: Code:
array=( $(sed --posix -n 's/[^0-9]*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)/\1\n/;t a;b;:a P;D' file | sort -u) ) |
Quote:
Thanks for the response - very comprehensive. Script now working; I appreciate everyone's time on this. Davee |
All times are GMT -5. The time now is 07:11 AM. |