5

I have a temp file, and I want to grep the only word that matches the pattern instead of whole word. i tried grep -o <pattern> file but its not giving me desired output

Input

xi29 vddf vss vddf vss int_s s2 rstb mg91a02_l_nd2_bulk_vt1 ln1=16n ln2=16n lp1=16n lp2=16n nf_n1=1 nf_n2=1 nf_p1=1 nf_p2=1  
xi28 vddf vss vddf vss d1 d mg91a02_l_inv_bulk_vt1 ln=16n lp=16n nf_n=1 nf_p=1 nfin_n=2 nfin_p=2 m=1  
xi25 vddf vss vddf vss int_m2 int_m1 mg91a02_l_inv_bulk_vt1 ln=16n lp=16n nf_n=1 nf_p=1 

Command

grep -o 'mg91a02' temp

Output (obtained)

mg91a02
mg91a02
mg91a02

Output (desired)

mg91a02_l_nd2_bulk_vt1
mg91a02_l_inv_bulk_vt1
mg91a02_l_inv_bulk_vt1
1
  • @garethTheRed i want output as above .. but all i get is mg9102 version grep (GNU grep) 2.5.1 Dec 9, 2014 at 7:46

3 Answers 3

7

try

 grep -E -o 'mg91a02\w+' 

where

  • -E : extended regexp
  • -o print only matched word
  • \w : word characters (alphanumerics or underscore, synonym for [_[:alnum:]]).
  • + one or more time

For non-whitespace characters, so as to catch strings with @ as per comment, see \S (short for [^[:space:]])

grep -E -o 'mg91a02\S+'

with edited input from the OP, this results in

mg91a02_l_inv_bulk_vt1
mg91a02_l_nd2_bulk_vt1
mg91a02_l_nd2_@bulk!_vt1
mg91a02_l_nd2_[bulk]_vt1
mg91a02_l_inv_bulk_vt1

Note that -o, \w and \S are non-standard extensions.

2
  • Hmm. \w doesn't seem to match only non-whitespace. For example I just saw it stop matching on a '@'.
    – Harv
    Nov 3 at 7:49
  • @Harv good catch, see my edit.
    – Archemar
    Nov 3 at 8:28
5
grep -o 'mg91a02[^ ]*' file

This means print pattern mg91a02 until not seen^ first space([^ ]) or means print everything which is not a space.

1

With Perl regular expressions:

grep -Po '\w*mg91a02\w*'

For example:

$ grep -Po top .zshrc
top
top
top
top
top
top
top
$ grep -Po '\w*top\w*' .zshrc
setopt
setopt
autopushd
setopt
setopt
setopt
setopt
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .