<a href="docs/2015-05-foobar/foobar.sh">foobar.sh</a>


<a href="foobar.sh">foobar.sh</a>

Question: How can I remove the "docs/2015-05-foobar/" ? The string could vary between the " 's

echo '<a href="docs/2015-05-foobar/foobar.sh">foobar.sh</a>' |\
  sed 's/\(.*\)href="\(.*\)\/\(.*\)"\(.*\)/\1href="\3"\4/'

gives you:

<a href="foobar.sh">foobar.sh</a>

If there is any context, I would however never use sed but a proper parser for the HTML to find the <a> entry, and then access the href of the element found using the access methods provided by the parser.

The \(.*\) parts match anything and what they match can be called back with \1, \3, etc.. The other characters (href=", \/, ") need to be matched (and the slash escaped as it is also used to denote the substitution pattern start and end. The matching is greedy, hence the \/ matches the last slash before the second ". By not using the match part with \2 that is dropped from the output, just as you wanted.


With sed:

$ echo '<a href="docs/2015-05-foobar/foobar.sh">foobar.sh</a>' |
  sed -e 's,".*/\([^/]*"\),"\1,'
<a href="foobar.sh">foobar.sh</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.