简体   繁体   English

从第n次出现的模式替换到sed的行尾

[英]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: 需要在第6次'/'后删除,包括自身:

/some/long/path/we/need

Using sed I came up with this solution, but it's kind of workaround-ish: 使用sed我提出了这个解决方案,但这是一种解决方法 - 是:

path=/some/long/path/we/need/to/shorten
slashesToKeep=5
n=2+slashesToKeep
echo $path | sed "s/[^/]*//$n;s/\/\/.*//g"

Cleaner solution much appreciated! 清洁解决方案非常感谢!

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 AWK解决方案

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

这可能适合你(GNU sed):

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

Awk: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM