0

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.

0

2 Answers 2

4

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.

10
  • 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
    Commented Feb 28, 2014 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
    Commented Feb 28, 2014 at 12:36
  • 1
    It works perfectly on Fedora 17 with GNU grep 2.14 here. +1 for the more elegant version.
    – erik
    Commented Feb 28, 2014 at 12:58
  • 1
    With recent versions of PCRE, see also: grep -Po 'a href="\K[^"]*' Commented Feb 28, 2014 at 13:18
  • 1
    That's a very good answer, @StephaneChazelas , I am learning a lot from you today :)
    – fedorqui
    Commented Feb 28, 2014 at 13:22
3
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.

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

You must log in to answer this question.

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