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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16382821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:21:39  来源:igfitidea点击:

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

linuxbashshellsed

提问by user1612686

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!

更清洁的解决方案非常感谢!

回答by Debaditya

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

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

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

回答by Fredrik Pihl

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