I want to split this line
/home/edwprod/abortive_visit/bin/abortive_proc_call.ksh
to
/home/edwprod/abortive_visit/bin
For most platforms and Unix/Linux shells now available dirname
:
dirname /home/edwprod/abortive_visit/bin/abortive_proc_call.ksh
Using of dirname
is the simpliest way, but it is not recommended for cross platform scripting for example in the last version of autoconf
documentation http://www.gnu.org/savannah-checkouts/gnu/autoconf/manual/autoconf-2.69/html_node/Limitations-of-Usual-Tools.html#Limitations-of-Usual-Tools .
So my full featured version of sed
-based alternative for dirname
:
str="/home/edwprod/abortive_visit/bin/abortive_proc_call.ksh"
echo "$str" | sed -n -e '1p' | sed -e 's#//*#/#g' -e 's#\(.\)/$#\1#' -e 's#^[^/]*$#.#' -e 's#\(.\)/[^/]*$#\1#' -
Examples:
It works like dirname
:
/aa/bb/cc
it will print /aa/bb
/aa/bb
it will print /aa
/aa/bb/
it will print /aa
too./aa/
it will print /aa
/
it will print /
aa
it will print .
aa/
it will print .
That is:
/
aa
and aa/
/
and the path /
itself.$str
if it contains \n
at the end or not, even with many \n
/
(//
///
) to /
Note
Alternative for basename
may be useful:
echo "$str" | awk -F"/" '{print $NF}' -