I want to grep a link from an external file example.txt.

example.txt containins:


the code:

egrep -o -m1 '(https)[^'\"]+.mp3' example.txt



When I run grep, it detect the last .mp3 as end of output while I just need it end after first occurrence. How can I tell grep to stop after finding the first pattern?

My desired output:


I just want to extract any string starting with https and ending with mp3

  • 1
    the + operator in grep is greedfy; you want a non-greedy match...
    – Jeff Schaller
    Commented Mar 5, 2016 at 13:03
  • no, I dont care about (and ). I just want to extract any string starting with https and ending with mp3
    – Sadegh
    Commented Mar 5, 2016 at 13:14
  • in my data after the links there are name of the files.it is not immediately after but it is somewhere in text.
    – Sadegh
    Commented Mar 5, 2016 at 13:18
  • @JeffSchaller I read the documentation. but i didn't understand what is non-greedy version of + . For instance ?+ or {1} also result in the same. Can you please tell me what is the non-greedy equivalent of + ? gexperts.org/tour/index.html?grep_regular_expressions.html
    – Sadegh
    Commented Mar 5, 2016 at 13:20
  • I read your regexp a little too quickly; your [] is telling grep to grab everything that's not a single- or double-quote. Does a ) always end your desired filename? [^)] would work in that case.
    – Jeff Schaller
    Commented Mar 5, 2016 at 13:40

3 Answers 3


Standard grep does not accept the ? modifier that would normally make it non-greedy.

But you can try the -P option that - if enabled in your distro - will make it accept Perl style regexes:

grep -oP -m1 "(https)[^'\"]+?.mp3" mp3.txt

If that does not work, you could for your specific example include the right parenthesis in the range so it wouldn't look beyond the parenthesis:

egrep -o -m1 "(https)[^'\")]+?.mp3" mp3.txt

egrep does not support non-greedy matching. Using perl mode -P will help you:

grep -o -m1 -P  'https.*?mp3' example.txt
~$ cat example.txt

~$ grep -Po "(https)[^'\"].*?mp3" example.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .