grep substring between quotes

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.

Asked By: polym

||

With GNU grep, you can do:

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

This should work only on the GNU version of grep:

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

Example on regex101 here.

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

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 
Answered By: Jignesh Patel

The command to select anything between quote is:

echo 'title="2010-09-11 11:22:45Z"' | grep -oP "(?<=").*(?=")"

If you want to select only if the text inside double quote match a particular regex, then replace .* with that regex.

For example,

echo 'title="2010-09-11 11:22:45Z"' | grep -oP "(?<=")[0-9-]{10} [0-9:]{8}Z(?=")"

Will match the timestamp but not the disregard me text.

Answered By: Ahmad Ismail
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.