Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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 replace the string


with the string


on the command line, probably using sed. I can't for the life of me figure out the replacement regex to pass to sed. Or maybe sed isn't even the right tool for the job. Any help would be appreciated.

share|improve this question
up vote 8 down vote accepted

no need for sed:

dirname /usr/local/bin/program

will return /usr/local/bin

share|improve this answer
Thanks Marcin, I knew this must have been simpler! – Alex Kahn Sep 29 '09 at 17:19
There is not even any need for dirname :-) . If the string is stored in $MYPROGRAM, then ${MYPROGRAM%/*} strips everything including and after the last slash, leaving you with the path to MYPROGRAM. This expansion behaviour is defined by POSIX. dirname handles relative paths and things like multiple slashes better, though. – Daniel Andersson Mar 28 '12 at 10:52
Neat! Which version of bash does it need to work? dirname is old and standard enough that it will work just about anywhere. – Marcin Mar 28 '12 at 15:21
@Marcin: it works with any Bash version; it is supposed to work with every standards (=POSIX) honoring shell. Also, on a separate note, if you respond to someone among the comments: if you start the comment with "@username", that user will be notified of the response through the site (I just found my comment by chance now, a week later). – Daniel Andersson Apr 4 '12 at 10:35

You must log in to answer this question.

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