grep substring between quotes

29,508

Solution 1

With GNU grep, you can do:

$ echo 'title="2010-09-11 11:22:45Z"' | grep -oP 'title="\K[^"]+'
2010-09-11 11:22:45Z

Solution 2

If input would be in this format only then below command will easily solve your problem

echo "title=\"2010-09-11 11:22:45Z\"| cut -d '"' -f2 

Solution 3

grep -oP '[0-9-]{10} [0-9:]{8}' filename

Solution 4

This should work only on the GNU version of grep:

<file.html grep -oP "(?<=title\=\")\d+-\d+-\d+"

Example on regex101 here.

Share:
29,508

Related videos on Youtube

polym
Author by

polym

[email protected]

Updated on September 18, 2022

Comments

  • polym
    polym almost 2 years

    Let's say I have a string like this:

    title="2010-09-11 11:22:45Z"
    

    How can I grep the date itself and disregard the quotes/title/Z?

    The file can contain more strings like:

    randomstring
    title="2010-09-11 11:22:45Z"
    title="disregard me"
    

    So I only want to grep timestamps with a single grep command.

    • groxxda
      groxxda almost 10 years
      sed 's/.*="\(.*\)"/\1/'
    • polym
      polym almost 10 years
      @Groxxda thanks, but is it possible in grep, too?
    • groxxda
      groxxda almost 10 years
      grep -o '".*"' | tr -d '"'
    • polym
      polym almost 10 years
      I don't get why this question is downvoted so often. It's a simple question: grep timestamps using one command only.
    • groxxda
      groxxda almost 10 years
      Are hours and day always two digits?
    • phemmer
      phemmer almost 10 years
      @polym This is probably being downvoted for a few reasons. 1) your original question mentioned html, and you should not attempt to regex through html. 2) you altered your question after it had been answered, to which the most upvoted answer is no longer a solution to the question. 3) this also is starting to sound like an X/Y problem, but this is just my own feeling, and probably not downvote worthy.
    • polym
      polym almost 10 years
      @Groxxda hours and days are always like it's represented above.
  • Buttle Butkus
    Buttle Butkus over 7 years
    no explanation, what is K?
  • cuonglm
    cuonglm over 7 years
    @ButtleButkus: \K is PCRE syntax, which don't include anything in left side of \K in matching result, or in Perl way, don't include in $&.
  • DimiDak
    DimiDak over 4 years
    thanx a lot man. If you could include also that each flag it's doing.. Would be perfect.