Take the 2-minute tour ×
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.

I want to parse a string for specific submatches and output those - one submatch per line - into a file.

Essentially I would like to extract the value of each href-attribute:

$ cat Fin
<a href="a.htm">A</a>X<a href="b.htm">B</a>Y<a href="c.htm">C</a>

$ echo Fin | [grep, sed, awk, ...?] > Fout

$ cat Fout
a.htm
b.htm
c.htm

I tried few things with named tools but things don't work or are too complicated. I would like to perform this transformation within a single command line concatenating as few as possible commands with piping.

share|improve this question

2 Answers 2

up vote 4 down vote accepted

You can use GNU grep (if built with PCRE support) for this:

$ grep -Po '(?<=a href=")[^"]*' file
a.htm
b.htm
c.htm

It is a look-behind (what's after a href="?) and gets everything up to next double quote.

share|improve this answer
    
I assume "file" is supposed to mean "Fin" - but no matter how I tweak your command - it is not going to give me the output you state. –  Raffael Feb 28 at 12:34
    
Yes, I wrote file but use the name of the file you are using. Aren't you getting the correct output? If so, please indicate the system in which you are working and the output you get. –  fedorqui Feb 28 at 12:36
1  
It works perfectly on Fedora 17 with GNU grep 2.14 here. +1 for the more elegant version. –  erik Feb 28 at 12:58
1  
With recent versions of PCRE, see also: grep -Po 'a href="\K[^"]*' –  Stéphane Chazelas Feb 28 at 13:18
1  
That's a very good answer, @StephaneChazelas , I am learning a lot from you today :) –  fedorqui Feb 28 at 13:22
sed 's%</a>%\n%g' Fin | sed 's%.*"\([a-z]\.htm\).*%\1%' > Fout
a.htm
b.htm
c.htm

Surely there is a shorter, more elegant way.

share|improve this answer
    
I tested the code and it does not seem to work as intended. The first line of Fout is as follows: "<a href=a.htm>A" –  Raffael Feb 28 at 12:31
    
Did you really use the exact same string as in your example? Here it works perfectly. –  erik Feb 28 at 12:56
    
There was a mistake on my side of the equation –  Raffael Feb 28 at 12:58
    
Well done! Note that cat file | sed '...' can be replaced by sed '...' file. –  fedorqui Feb 28 at 12:59

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.