22

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?

Community
  • 1
  • 1
NoobEditor
  • 15,563
  • 19
  • 81
  • 112
  • You should copy/paste code/terminal output, rather than post a screenshot. Your screenshot is difficult to read, you can't copy/paste from it, and can't edit it (should this be required). – Martin Tournoij Jul 02 '14 at 09:27
  • It looks like you're not using GNU grep; which OS are you using? Does `grep -V` or `grep --version` say anything about the version? – Martin Tournoij Jul 02 '14 at 09:28
  • posted screen shot not visible properly. Also as 5K rep people should post question nicely. – Jayesh Bhoi Jul 02 '14 at 09:29
  • @Jayesh : updated with code! :) – NoobEditor Jul 02 '14 at 09:30
  • @Carpetsmoker : it says : `Usage: grep -hblcnsviw pattern file . . .` – NoobEditor Jul 02 '14 at 09:32
  • You need to download the GNU grep version,[from](http://www.sunfreeware.com/introduction.html) – Jayesh Bhoi Jul 02 '14 at 09:34
  • @Jayesh : this is a remote server, installation is not in my hand...i need some solution through programming only! – NoobEditor Jul 02 '14 at 09:35
  • if you don't have gnu grep and don't have gnu awk either. I hope you have nawk on your SunOs. There is no shortcut to print those matched part out, you have to use nawk's `match()` and get the matched position and length, extract it, print, then search next match. – Kent Jul 02 '14 at 10:01
  • @Tiago : nope...but i really liked your answer, +1 to it!! :) – NoobEditor Jul 02 '14 at 10:09

2 Answers2

16

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
Community
  • 1
  • 1
damienfrancois
  • 52,978
  • 9
  • 96
  • 110
5

If you have perl :

echo "I am a boy" | perl -lne '/am/ && print $&'
am
Tiago Lopo
  • 7,619
  • 1
  • 30
  • 51