Pick out a range of characters with non-greedy grep

Let's say you've got a string like:

$ string="abc.Cat.def.1.zip.hij.Cut.klm.1.zip.Cat.no.2.zippqrs"

Out of this string, you want to pick out Cat*zip (Cat.def.1.zip and Cat.no.2.zip), ".*" works but is greedy so this grabs too much:

$ echo $string | grep -Eo "Cat.*zip"
Cat.def.1.zip.hij.Cut.klm.1.zip.Cat.no.2.zip

This does what we want:

$ echo $string | grep -Eo "Ca[t][^t]*.zip"
Cat.def.1.zip
Cat.no.2.zip

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).