tags:

views:

43

answers:

3

How to remove the last dir with sed, like this:

echo "/dir1/dir2/dir3/dir4" | sed .....

So I would get /dir1/dir2/dir3.

+2  A: 
sed 's,/*[^/]\+/*$,,'

If it's part of the shell script, then dirname will be definitely more clear.

przemoc
+2  A: 

echo "/etc1/etc2/etc3/etc" | sed -e "s/\/[^\/]*$//"

produces

/etc1/etc2/etc3

Basically strip off anything at the end after the last slash that doesn't contain another slash.

Shawn D.
Oops, using commas as the delimiter like przemoc indicated would be better to avoid having to escape the slashes in the script, making it more readable. I always make that mistake.
Shawn D.
+1  A: 

you don't have to use external tools

$ a="/dir1/dir2/dir3/dir4"

$ echo ${a%/*}

ghostdog74