Use grep with regular expression to extract specific substring (-o, –only-matching)

By neokrates, written on July 7, 2010

bash   snippet

Rate it
  • 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
    Loading ... Loading ...
Ad
Poll
  • Estimate your experience level with Virtualization technology?

    • No experience (100%, 4 Votes)
    • Guru (0%, 0 Votes)
    • Expert / Admin (0%, 0 Votes)
    • Professional / Developer (0%, 0 Votes)
    • User (0%, 0 Votes)
    • Beginner (0%, 0 Votes)
    • Have tried (0%, 0 Votes)

    Total Voters: 4

    Vote

    Loading ... Loading ...
Feeds:
  • bodytext bodytext bodytext
Most popular search terms:

I have a file with some random text and I wish a very specific part of it to be assigned to my bash variable.

File:

$ cat grepme.txt
My name is &&&neokrates3223
My name is neokrates--
My name is tadada
Ma name is not neokrites

 
And I wish to know the name.

Suppose, the correct name can be identified:
[star] it is prefixed by “My name is”;
[star] it is surrounded by &&& and some numbers;

I use some grep with pipe to extract the name:

MY_NAME=$(grep -o "My name is [\&\/a-zA-Z0-9\-]*" grepme.txt |grep -o "&[\&\/a-zA-Z0-9\-]*" | grep -o "[a-zA-Z]*" ; echo -e "\n\nYour name is $MY_NAME\n\n"

 

I get:

 
 
Your name is neokrates

 
Have fun ;)

 
Does that help to solve your problem?
VN:F [1.8.5_1061]
Rating: -1 (from 3 votes)
1 votes 'YES'  2 votes 'NO'
TAGS
No tags for this post.
RELATED
Pages
Posts
    nope :(
SOCIAL
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • BlinkList
  • Blogosphere News
  • E-mail this story to a friend!
  • Furl
  • LinkArena
  • Live
  • MisterWong
  • Print this article!
  • StumbleUpon
  • Technorati
  • Webnews.de
  • YahooMyWeb

2 Responses to “Use grep with regular expression to extract specific substring (-o, –only-matching)”

  1. blake says:

    there is no closing bracket. also im fairly sure the output of grep -o cannot be piped to another grep – at least its not working for me….

    Like or Dislike: Thumb up 0 Thumb down 0

    • admin says:

      Hi Blake,

      you are right about bracket, publishing problem I guess.

      Grep can be generally piped. What Version of grep and under which Os fails to pipe “grep -o“?

      Like or Dislike: Thumb up 0 Thumb down 0

Leave a Reply