user1612686
user1612686

Reputation: 178

Replace from nth occurrence of pattern till the end of line with sed

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

Answers (3)

Fredrik Pihl
Fredrik Pihl

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

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed 's/\/[^\/]*//6g' file

Upvotes: 4

Debaditya
Debaditya

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

Related Questions