Reputation: 178
For example:
/some/long/path/we/need/to/shorten
Need to delete after the 6th occurrence of '/', including itself:
/some/long/path/we/need
Using sed I came up with this solution, but it's kind of workaround-ish:
path=/some/long/path/we/need/to/shorten
slashesToKeep=5
n=2+slashesToKeep
echo $path | sed "s/[^/]*//$n;s/\/\/.*//g"
Cleaner solution much appreciated!
Upvotes: 2
Views: 5731
Reputation: 45670
Awk:
awk -F'/' 'BEGIN{OFS=FS}{NF=6}1'
In action:
$ echo /some/long/path/we/need/to/shorten | awk -F'/' 'BEGIN{OFS=FS}{NF=6}1'
/some/long/path/we/need
Upvotes: 2
Reputation: 2497
Input
/some/long/path/we/need/to/shorten
Code
Cut Solution
echo '/some/long/path/we/need/to/shorten' | cut -d '/' -f 1-6
AWK Solution
echo '/some/long/path/we/need/to/shorten' | awk -F '/' '{ for(i=1; i<=6; i++) {print $i} }' | tr '\n' '/'|sed 's/.$//'
Output
/some/long/path/we/need
Upvotes: 6