How to extract the matching part of a regex on Solaris

grepregexsolaris

GNU's grep has the option --only-matching, which prints just the matching region of a regular expression. I'm on a Solaris 5.10 box without any GNU tools installed, and I'm trying to achieve the same thing. Example:

grep -Eo "[0-9]+ ms" *.log

Is there a sed or awk expression that can do the same thing?

Best Answer

sed -n 's/.*[^0-9]\([0-9]\+ ms\).*/\1/p' *.log

A possible refinement for versions of sed which support this type of alternation:

sed -n 's/\(^\|.*[^0-9]\)\([0-9]\+ ms\).*/\2/p' *.log

In OS X, I had to use extended regular expressions because I couldn't get basic enhanced regular expressions to work (this would work in GNU sed, too, if you change -E to -r, but the basic enhanced version works there, too):

sed -En 's/(^|.*[^0-9])([0-9]+ ms).*/\2/p' *.log

These two latter examples work even if the sequence you're searching for appears at the beginning of the line with no leading characters.

Related Topic