Extracting directory name from an absolute path using sed or awk

后端 未结 6 1172
忘掉有多难
忘掉有多难 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:16

    In addition, to the answer of Kent, an alternative awk solution is:

    awk 'BEGIN{FS=OFS="/"}{NF--}1'
    

    which has the same sickness as the one presented by Kent. The following, somewhat longer Awk corrects all the flaws:

    awk 'BEGIN{FS=OFS="/"}{gsub("/+","/")}
         {s=$0~/^\//;NF-=$NF?1:2;$0=$0?$0:(s?"/":".")};1' 
    

    The following table shows the difference:

    | path       | dirname | awk full | awk short |
    |------------+---------+----------+-----------|
    | .          | .       | .        |           |
    | /          | /       | /        |           |
    | foo        | .       | .        |           |
    | foo/       | .       | .        | foo       |
    | foo/bar    | foo     | foo      | foo       |
    | foo/bar/   | foo     | foo      | foo/bar   |
    | /foo       | /       | /        |           |
    | /foo/      | /       | /        | /foo      |
    | /foo/bar   | /foo    | /foo     | /foo      |
    | /foo/bar/  | /foo    | /foo     | /foo/bar  |
    | /foo///bar | /foo    | /foo     | /foo//    |
    

    note: dirname is the real way to go, unless you have to process masses of them stored in a file.

提交回复
热议问题