1

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?

brianegge
  • 1,064
  • 2
  • 14
  • 23

3 Answers3

3
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.

Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
0

Try using /usr/sfw/bin/ggrep

/usr/sfw/bin/ggrep -V grep (GNU grep) 2.5

Copyright 1988, 1992-1999, 2000, 2001 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

>

Haggertus
  • 11
  • 1
  • 1
    Nope. The sfw packages aren't installed, and I don't have access to install them. The only directory I can write to is /tmp, and it would be easier to copy the files back to a machine with gnu grep on it than to copy grep to /tmp. – brianegge Feb 11 '10 at 00:24
0

Solaris 5.10 includes bash 3.00, which has a modern regex engine. The follow command works, though it's quite a bit more verbose than a grep or sed solution.

cat *.log | while read line; 
do 
  if [[ $line =~ "([0-9]+) ms" ]]; then 
    echo "${BASH_REMATCH[1]}"; 
  fi;
done 

(Formatted on multiple lines for readability)

brianegge
  • 1,064
  • 2
  • 14
  • 23
  • Bash regex handling changed for version 3.2. You should not quote the pattern because it will be treated as a literal string instead of a regex. Since unquoted patterns also work in Bash 3.0 and 3.1, you should use them there, too, for forward compatibility. Further, I recommend that the pattern be stored in a variable and the variable should be used on the right side of `=~`. For example: `pattern='([0-9]+) ms'; if [[ $line =~ $pattern ]]` – Dennis Williamson Sep 18 '13 at 15:33