bash: extracting last two dirs for a pathname

前端 未结 7 952
灰色年华
灰色年华 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:16

    I don't know of a method specifically for trimming paths, but you can certainly do it with bash's regular expression matching:

    DIRNAME=/a/b/c/d/e
    if [[ "$DIRNAME" =~ ([^/]+/+[^/]+)/*$ ]]; then
        echo "Last two: ${BASH_REMATCH[1]}"
    else
        echo "No match"
    fi
    

    Note: I've made the pattern here a little more complex than you might expect, in order to handle some allowed-but-not-common things in the path: it trims trailing slashes, and tolerates multiple (redundant) slashes between the last two names. For example, running it on "/a/b/c//d//" will match "c//d".

提交回复
热议问题