Question

I am trying to use

grep -o "javascript:add2BasketProd.*?jpg"

to extract string from

javascript:add2BasketProd('xKonfGFJsakj', 'Tattoo-Bubble-Gum-7cm-Bubble-Gum.jpg')Funny-Glasses-and-Teeth-Toy-Candy-TC-747-.jpg 

but it would give no output. So I changed the code to the following but the output I get is entire string and not until the first match of jpg.

grep -o "javascript:add2BasketProd.*\?jpg" 

My expected output is:

javascript:add2BasketProd('xKonfGFJsakj', 'Tattoo-Bubble-Gum-7cm-Bubble-Gum.jpg

Can anyone suggest a solution?

Was it helpful?

Solution

grep uses POSIX style regular expression which are always greedy. If your grep supports the -P flag, you can use it to enable perl style regex which do support non-greedy matches:

grep -oP "javascript:add2BasketProd.*?jpg" 

The GNU grep, which is used on linux, supports -P. The Mac OSX grep does not.

OTHER TIPS

You can use egrep for advanced regex capabilities:

s='javascript:add2BasketProd('xKonfGFJsakj', 'Tattoo-Bubble-Gum-7cm-Bubble-Gum.jpg')Funny-Glasses-and-Teeth-Toy-Candy-TC-747-.jpg'
egrep -o "javascript:add2BasketProd.*?jpg" <<< "$s"
javascript:add2BasketProd(xKonfGFJsakj, Tattoo-Bubble-Gum-7cm-Bubble-Gum.jpg
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top