I have to write a shell script to get value from a string, something like:

string="abcdef" pathName

How can I use grep command with the use of regular expression to get "pathName"?

  • using bash ? ....
    – guido
    Sep 15, 2012 at 8:46

1 Answer 1


GNU grep has the --only-matching option:

echo 'string="abcdef" pathName' |grep --only-matching "pathName"

will output "pathName".

Update with more info on the required pattern:

echo 'string="abcdef" pathName' |grep --only-matching "[[:graph:]]*$"

Here [[:graph:]] is the character class of all non-space characters, * means zero-or-more of the preceding pattern, $ means end-of-line.
So the pattern matches the longest sequence of non-space characters at the end of the line.

  • but I don't know what exactly "pathName" is. It can be a sequence of characters anything. In particular, I need a regular expression to get it.
    – cat916
    Sep 15, 2012 at 8:30
  • You need to know something about the input string in order to construct a regex. If there are no space characters in "pathName" you could use "[[:graph:]]*$". Sep 15, 2012 at 8:39
  • thank you very much... can you explain it to me ?
    – cat916
    Sep 15, 2012 at 8:50
  • @minhcat_vo I've updated my answer to explain the pattern. Sep 15, 2012 at 9:05

You must log in to answer this question.

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