Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

example.txt containins:

(https://example.com/pathto/music.mp3)music.mp3

the code:

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

output:

https://example.com/pathto/music1.mp3)music.mp3

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:

https://example.com/pathto/music.mp3

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

share|improve this question
1  
the + operator in grep is greedfy; you want a non-greedy match... – Jeff Schaller Mar 5 at 13:03
    
no, I dont care about (and ). I just want to extract any string starting with https and ending with mp3 – Woeitg Mar 5 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. – Woeitg Mar 5 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 – Woeitg Mar 5 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 Mar 5 at 13:40
up vote 3 down vote accepted

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
share|improve this answer

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

grep -o -m1 -P  'https.*?mp3' example.txt
share|improve this answer
~$ cat example.txt
(https://example.com/pathto/music.mp3)music.mp3

~$ grep -Po "(https)[^'\"].*?mp3" example.txt
https://example.com/pathto/music.mp3
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.