例如:
/some/long/path/we/need/to/shorten
需要在第6次'/'后删除,包括其自身:
/some/long/path/we/need
使用sed我想出了这个解决方案,但这是一种解决方法 - ish:
path=/some/long/path/we/need/to/shorten
slashesToKeep=5
n=2+slashesToKeep
echo $path | sed "s/[^/]*//$n;s/\/\/.*//g"
清洁解决方案非常感谢!
答案 0 :(得分:5)
<强>输入强>
/some/long/path/we/need/to/shorten
代码
剪切解决方案
echo '/some/long/path/we/need/to/shorten' | cut -d '/' -f 1-6
AWK解决方案
echo '/some/long/path/we/need/to/shorten' | awk -F '/' '{ for(i=1; i<=6; i++) {print $i} }' | tr '\n' '/'|sed 's/.$//'
<强>输出强>
/some/long/path/we/need
答案 1 :(得分:4)
这可能适合你(GNU sed):
sed 's/\/[^\/]*//6g' file
答案 2 :(得分:2)
awk中:
awk -F'/' 'BEGIN{OFS=FS}{NF=6}1'
行动中:
$ echo /some/long/path/we/need/to/shorten | awk -F'/' 'BEGIN{OFS=FS}{NF=6}1'
/some/long/path/we/need