UNIX sed替代第n次发生功能故障? [英] unix sed substitute nth occurence misfunction?

查看:94
本文介绍了UNIX sed替代第n次发生功能故障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串,其中包含字母Z的多次出现. 例如:aaZbbZccZ. 我想每次直到下一次出现Z时都打印该字符串的一部分:

Let's say I have a string which contains multiple occurences of the letter Z. For example: aaZbbZccZ. I want to print parts of that string, each time until the next occurence of Z:

aaZ
aaZbbZ
aaZbbZccZ

因此,我尝试通过命令sed s/Z.*/Z/i为此使用unix sed,其中i是从1到字符串中Z的个数的索引.就我的理解而言:这应该删除第i个Z之后的所有内容,但是实际上,这仅在我具有sed s/Z.*/Z/中的i = 1时才有效,但不能像在例如,仅打印整个原始字符串.感觉好像我缺少sed的功能,因为根据多本手册,它应该可以工作.

So I tried using unix sed for this, with the command sed s/Z.*/Z/i where i is an index that I have running from 1 to the number of Z's in the string. As far as my sed understanding goes: this should delete everything that comes after the i'th Z, But in practice this only works when I have i=1 as in sed s/Z.*/Z/, but not as I increment i, as in sed s/Z.*/Z/2 for example, where it just prints the entire original string. It feels as if there's something I am missing about the functioning of sed, since according to multiple manuals, it should work.

例如,在应用sed s/Z.*/Z/2时在字符串aaZbbZccZ中,我希望具有aaZbbZ,因为Z的第二次出现后的所有内容都将被删除.

edit: for example, in the string aaZbbZccZ while applying sed s/Z.*/Z/2 I am expecting to have aaZbbZ, as everything after the 2nd occurence of Z get's deleted.

推荐答案

下面的sed与您要查找的内容非常接近,除了它还会删除最后一个Z.

Below sed works closely to what you are looking for, except it removes also the last Z.

$echo aaZbbZccZdd | sed -e 's/Z[^Z]*//1g;s/$/Z/'
aaZ

$echo aaZbbZccZdd | sed -e 's/Z[^Z]*//2g;s/$/Z/'
aaZbbZ

$echo aaZbbZccZdd | sed -e 's/Z[^Z]*//3g;s/$/Z/'
aaZbbZccZ

$echo aaZbbZccZdd | sed -e 's/Z[^Z]*//4g;s/$/Z/'
aaZbbZccZddZ

根据亚伦的建议进行了修改.

Modified according to Aaron suggestion.

Edit2: 如果您不知道字符串中有多少个Z,使用下面的命令会更安全.否则,将在末尾添加其他Z.
-r-启用正则表达式
-e-分隔sed操作,与;相同,但在我看来更易于阅读.

If you don't know how many Z there are in the string it's safer to use below command. Otherwise additional Z is added at the end.
-r - enables regular expressions
-e - separates sed operations, the same as ; but easier to read in my opinion.

$echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//1g' -e 's/([^Z])$/\1Z/'
aaZ

$echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//2g' -e 's/([^Z])$/\1Z/'
aaZbbZ

$echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//3g' -e 's/([^Z])$/\1Z/'
aaZbbZccZ

$echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//4g' -e 's/([^Z])$/\1Z/'
aaZbbZccZddZ

$echo aaZbbZccZddZ | sed -r -e 's/Z[^Z]*//5g' -e 's/([^Z])$/\1Z/'
aaZbbZccZddZ

这篇关于UNIX sed替代第n次发生功能故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆