Extracting directory name from an absolute path using sed or awk

后端 未结 6 1069
忘掉有多难
忘掉有多难 2021-01-05 13:29

I want to split this line

/home/edwprod/abortive_visit/bin/abortive_proc_call.ksh

to

/home/edwprod/abortive_visit/bin
         


        
6条回答
  •  天涯浪人
    2021-01-05 14:19

    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:

    • For path like /aa/bb/cc it will print /aa/bb
    • For path like /aa/bb it will print /aa
    • For path like /aa/bb/ it will print /aa too.
    • For path like /aa/ it will print /aa
    • For path like / it will print /
    • For path like aa it will print .
    • For path like aa/ it will print .

    That is:

    • It works correct with trailing /
    • It works correct with paths that contains only base name like aa and aa/
    • It works correct with paths starting with / and the path / itself.
    • It works correct with any $str if it contains \n at the end or not, even with many \n
    • It uses cross platform sed command
    • It changes all combinations of / (// ///) to /
    • It can't work correct with paths containing newlines and characters invalid for current locale.

    Note Alternative for basename may be useful:

    echo "$str" | awk -F"/" '{print $NF}' -
    

提交回复
热议问题