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 '12 at 8:46

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.

| improve this answer | |
  • 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. – cat_minhv0 Sep 15 '12 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:]]*$". – donothingsuccessfully Sep 15 '12 at 8:39
  • thank you very much... can you explain it to me ? – cat_minhv0 Sep 15 '12 at 8:50
  • @minhcat_vo I've updated my answer to explain the pattern. – donothingsuccessfully Sep 15 '12 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.