取代多达n次的比赛 [英] replace up to nth match

查看:109
本文介绍了取代多达n次的比赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 SED 阅读 可以取代所有比赛开始的第二个


  

您可以用g(全局)标志相结合的数字。举例来说,如果你想
  单独留下的第一个字,但改变第二,第三等被删除
  相反,使用/ 2G:


例如

  SED的/富/酒吧/ 2GA.TXT

但你怎么能取代匹配的最高第二,使第三,第四等不会受到影响?类似

  SED的/富/酒吧/ 1-2'A.TXT


解决方案

这可能会为你工作(GNU SED):

  SED的/富/&安培; \\ N / 2;吨; H; S //酒吧/克; G组; S / \\ N * \\ n //'文件

本身和一个换行符替换字符串预期的第n个occurence。
如果置换失败拯救别人的模式空间(PS)复制到保留空间(HS)。
使用替换字符串进行替换,然后重建与改变行原线。

还有:

  SED的/富/ \\ N /克; S / \\ n /富/ 3G; S / \\ N /酒吧/ g的'文件

其中第n +1代替1到第n个

With sed I read that you can replace all matches starting with the second

You can combine a number with the g (global) flag. For instance, if you want to leave the first word alone, but change the second, third, etc. to be DELETED instead, use /2g:

example

sed 's/foo/bar/2g' a.txt

However how could you replace matches up to the second, so that the third, fourth, etc are not affected? Something like

sed 's/foo/bar/1-2' a.txt

解决方案

This might work for you (GNU sed):

sed 's/foo/&\n/2;T;h;s//bar/g;G;s/\n.*\n//' file

Replace the nth occurence of the intended string by itself and a newline. If the substitution fails bail out else copy the pattern space (PS) to the hold space (HS). Make the substitution using the replacement string and then reconstitute the original line with the altered line.

Also:

sed 's/foo/\n/g;s/\n/foo/3g;s/\n/bar/g' file

Where nth +1 is used instead of the 1 to the nth

这篇关于取代多达n次的比赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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