2

I want to get a list of strings matching the following pattern:

CLASS_NAME:"*"

where * represents any number of characters.

I tried:

grep -o CLASS_NAME:\".*\" script.js

and

grep -o CLASS_NAME:\"*\" script.js

The first case returns the entire line after the matched string while the second case terminates at the first ". How can I get it to return just the matched string?

  • grep -o 'CLASS_NAME:".*"' script.js – mikeserv Apr 2 '14 at 12:41
  • @mikeserv, nope, it doesn't work. Got same result as my first case. – Question Overflow Apr 2 '14 at 12:43
  • Is there actually another quote mark on the same line? And you definitely used the single'quotes? Cause I just tested it and it worked... Maybe you just don't want spaces? grep -o 'CLASS_NAME:[^ ]*' – mikeserv Apr 2 '14 at 12:45
  • 1
    Ah, you are right. There are more than two quotation marks on the single line. That's why it is returning more than what I required. I need to extract all class names from the minified script. Anyway to prevent that? – Question Overflow Apr 2 '14 at 12:48
  • 1
    This is what you do: grep -o 'CLASS_NAME:"[^"]*"' script.js - that'll ensure you only match to the very next double-quote and nothing more. – mikeserv Apr 2 '14 at 12:52
6

Ok, so I guess your problem was that multiple-quote marks per line were pulling in more than you wanted because regex is inherently greedy - it will always match as much as possible if it can.

So the solution is to ensure you only match between the two double-quote marks, like:

grep -o 'CLASS_NAME:"[^"]*"' script.js

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.