How to get first N parts of a path?

前端 未结 1 964
暗喜
暗喜 2021-01-26 22:03

Imagine a path like this: /a/b/c/d/e/...

Where ... could be any number of levels further deep, i.e., I don\'t know, ahead of time, whether ther

相关标签:
1条回答
  • 2021-01-26 22:22

    You can use cut:

    s='/a/b/c/d/e/f/g/h/i/j/k'
    echo "$s" | cut -d/ -f1-5
    /a/b/c/d
    

    Or if you are using BASH then you can use shell array:

    IFS=/ arr=($s)
    

    Then print desired elements from array:

    IFS=/ echo "${arr[*]:0:5}"
    /a/b/c/d
    
    0 讨论(0)
提交回复
热议问题