Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only matching word, not entire line through grep

Tags:

grep

unix

solaris

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?

like image 793
NoobEditor Avatar asked Jul 02 '14 09:07

NoobEditor


People also ask

How do you print only the matched pattern using grep?

-f file : Takes patterns from file, one per line. -E : Treats pattern as an extended regular expression (ERE) -w : Match whole word -o : Print only the matched parts of a matching line, with each such part on a separate output line.

How do I grep only match in word?

To Show Lines That Exactly Match a Search String The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

How do I print over a line in grep?

It is possible to print a line above or below (or both) a line having a pattern using grep by using -A , -B or -C flags with num value. Here num denotes the number of additional lines to be printed which is just above or below the matched line.

How do I exclude items from grep?

Exclude Words and Patterns To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters).


2 Answers

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
like image 58
damienfrancois Avatar answered Oct 12 '22 12:10

damienfrancois


If you have perl :

echo "I am a boy" | perl -lne '/am/ && print $&'
am
like image 37
Tiago Lopo Avatar answered Oct 12 '22 12:10

Tiago Lopo