How to get first N parts of a path?

耗尽温柔 提交于 2020-11-29 10:14:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!