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

By neokrates, written on July 7, 2010

bash   snippet

  • Join date: 11-30-99
  • Posts: 224
View Counter:
Rate it
  • What would describe state of logging infrastructure of your enterprise best?

    View Results

    Loading ... Loading ...
  • bodytext bodytext bodytext

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


$ 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:

⭐ it is prefixed by “My name is”;

⭐ 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 ;)

Be Sociable, Share!
Does that help to solve your problem?
VN:F [1.8.5_1061]
Rating: -2 (from 4 votes)
1 votes 'YES'  3 votes 'NO'
No tags for this post.
Be Sociable, Share!

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….

    • 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“?

Leave a Reply