How to remove the last directory from a path using sed (without using dirname)?

How to delete the last directory with sed, for example:

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

So, I would get /dir1/dir2/dir3 .

+7
sed
source share
4 answers
 sed 's,/*[^/]\+/*$,,' 

If this is part of a shell script, then dirname will definitely be more understandable.

+7
source share

you do not need to use external tools

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

$ echo ${a%/*}

+24
source share

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

produces

/ ETC1 / ETC2 / etc3

Basically, cross out anything at the end after the last slash that does not contain another slash.

+3
source share

you can use the dirname shell command:

 dirname /dir2/dir3/dir4 
0
source share

All Articles