Print only matching word, not entire line through grep

NoobEditor picture NoobEditor · Jul 2, 2014 · Viewed 39.6k times · Source

I am familiar with shell programming in bash, but for some reason egrep -o to print only matching words is not working and displays error as below.

Environment is ksh unix console on putty and not linux or ubuntu terminal......any advice is appreciated!

Terminal input & output :

AB12 $ echo "i am a boy" | grep -w "am"
i am a boy
AB12 $ echo "i am a boy" | egrep -o "am"
egrep: illegal option -- o
usage: egrep [ -bchilnsv ] [ -e exp ] [ -f file ] [ strings ] [ file ] ...
AB12 $ echo$
ksh: echo$: not found
AB12 $ echo $SHELL
/bin/ksh
AB12 $ echo "i am a boy" | grep -o "am"
grep: illegal option -- o
Usage: grep -hblcnsviw pattern file . . .
AB12 $

PS : Similar thread but tried already : Can grep show only words that match search pattern?

Answer

damienfrancois picture damienfrancois · Jul 2, 2014

I am assuming this is a Solaris box you are connecting to. Solaris' version of grep does not have the -o option. So you can either

  • install the GNU grep on your Solaris box (it might already be installed in /usr/sfw/bin, or you might have luck with pkg install //solaris/text/gnu-grep); or
  • use awk instead (see this SO question)

See on my box:

$ uname
SunOS
$  echo "i am a boy" | grep -o "am"
grep: illegal option -- o
Usage: grep -hblcnsviw pattern file . . .
$  echo "i am a boy" | /usr/sfw/bin/ggrep -o "am"
am