问题
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 there will be 2, 3, or 13 more level deep.
How can I, using a FreeBSD shell, e.g., /bin/sh
, extract the first "N" parts of this path? e.g., first 4 levels, so that I would get /a/b/c/d
?
回答1:
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
来源:https://stackoverflow.com/questions/41229950/how-to-get-first-n-parts-of-a-path