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 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

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
up vote 4 down vote accepted

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

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

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 '14 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 '14 at 12:36
It works perfectly on Fedora 17 with GNU grep 2.14 here. +1 for the more elegant version. – erik Feb 28 '14 at 12:58
With recent versions of PCRE, see also: grep -Po 'a href="\K[^"]*' – Stéphane Chazelas Feb 28 '14 at 13:18
That's a very good answer, @StephaneChazelas , I am learning a lot from you today :) – fedorqui Feb 28 '14 at 13:22
sed 's%</a>%\n%g' Fin | sed 's%.*"\([a-z]\.htm\).*%\1%' > Fout

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 '14 at 12:31
Did you really use the exact same string as in your example? Here it works perfectly. – erik Feb 28 '14 at 12:56
There was a mistake on my side of the equation – Raffael Feb 28 '14 at 12:58
Well done! Note that cat file | sed '...' can be replaced by sed '...' file. – fedorqui Feb 28 '14 at 12:59

Your Answer


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.