bash: extracting last two dirs for a pathname

前端 未结 7 964
灰色年华
灰色年华 2021-02-12 12:42

I seem to have failed at something pretty simple, in bash. I have a string variable that holds the full path to a directory. I\'d like to assign the last two di

7条回答
  •  礼貌的吻别
    2021-02-12 13:22

    function getDir() {
    echo $1 | awk -F/ '
    {
        n=NF-'$2'+1;
        if(n<1)exit;
        for (i=n;i<=NF;i++) {
            printf("/%s",$i);
        }
    }'
    }
    
    dir="/a/b/c/d/e"
    dir2=`getDir $dir 1`
    echo $dir2
    

    You can get any number of directories from the last from this function. For your case run it as,

    dir2=`getDir $dir 2`;
    

    Output : /d/e

提交回复
热议问题