I am trying to figure out why this command is not working for me:

sed -n -e '/<a href=\(.*\)>/,/<\/a>/p' text.html

On text.html we have something like...

<somestupidstuff> <a href='teste'> teste </a> </somestupidstuff>

The desired output is:

<a href='teste'> teste </a>

But what I get is:

<somestupidstuff> <a href='teste'> teste </a> </somestupidstuff>

Maybe I am not fully understanding the regex.

  • What your sed expression is doing is printing all the lines between the matches of /<a href=\(.*\)>/ and of /<\/a>/. If this is a well formed XML document, you may want to look into using an XML parser instead, such as xmlstarlet.
    – Kusalananda
    Dec 2, 2019 at 14:12

1 Answer 1


It's much easier to use grep for your case. E.g. this way:

grep -o '<a href=[^<]*<\/a>'

In case there are < between <a href>..</a> you might want to try this instead:

grep -o '<a href=.*<\/a>'

However pay attention that it might return a data you don't expect for strings where you have multiple <a href=...</a> occurrences in the same string.

sed doesn't work for you because /pattern1/,/pattern2/p instructs sed to print all lines between line with pattern1 to line with pattern2 (including lines with patterns).

The problem might be solved with sed as well, but it depends on somestupidstuff content (e.g. whether it's the same in all cases or not, etc)

  • It is better but I am still having trouble, I dont see anything like a href beetween the strings, but it is still breaking it for some unknow reason. I will try to be more specific... Dec 2, 2019 at 14:22
  • A lot of ocurrencies of <a href=***> blabla </a> are being ignored the lines are very long like the results of a google search for example, this is giving me some heartaches, but I cant understand why something simple like that can be so unexpected. Dec 2, 2019 at 14:24
  • @LucianoAndressMartini Do you have any additional spaces between a and href? Do you have multi line entries where <a starts on one line and </a> ends on another line? (grep in a way I posted it doesn't expect multi-line entries)
    – rush
    Dec 2, 2019 at 14:30
  • ah. you have < between <a href>..</a>' while grep` doesn't expect it. I'll update the answer.
    – rush
    Dec 2, 2019 at 14:41

You must log in to answer this question.

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