tags:

views:

34

answers:

2

I have a string like first url, second url, third url and would like to extract only the url after the word second in the OS X Terminal (only the first occurrence). How can I do it?

In my favorite editor I used the regex /second (url)/ and used $1 to extract it, I just don't know how to do it in the Terminal.

Keep in mind that url is an actual url, I'll be using one of these expressions to match it: http://stackoverflow.com/questions/1141848/regex-to-match-url

+1  A: 
echo 'first url, second url, third url' | sed 's/.*second//'

Edit: I misunderstood. Better:

echo 'first url, second url, third url' | sed 's/.*second \([^ ]*\).*/\1/'

or:

echo 'first url, second url, third url' | perl -nle 'm/second ([^ ]*)/; print $1'
Sjoerd
That returns ` url, third url` =/
bfred.it
The third command works best (no need to escape parenthesis and such = great) but it returns all the occurrences (with my input, a long file, 13 times each), I would just need the first
bfred.it
I added an inelegant `| sed -n '1 s/\./\./p'` after the perl command and everything worked out fine =DThank you!
bfred.it
+1  A: 

In the other answer provided you still remain with everything after the desired URL. So I propose you the following solution.

echo 'first url, second url, third url' | sed 's/.*second \(url\)*.*/\1/'

Under sed you group an expression by escaping the parenthesis around it (POSIX standard).

mhitza
A +1 for the info about the escape =)
bfred.it