替换标志中的多个数字或“g”

时间:2022-08-11 02:45:06

when I use sed in mac OS, I can't use substitute flags like this:

当我在mac OS中使用sed时,我不能使用这样的替代标志:

sed 's/xx/yy/3g' my.txt 

what's the replacement for this command? I cannot use "3g" together here. This use case is in the reference documentation.

这个命令的替代品是什么?我不能在这里同时使用3g。这个用例在参考文档中。

I use BSD sed. It show error:

我使用BSD sed。它显示错误:

more than one number or 'g' in substitute flags

2 个解决方案

#1


1  

This might work for you (GNU sed):

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

sed 's/x/\ny/3;h;s/x/y/g;H;g;s/\n.*\n//' file

Place a unique marker after the occurences you want to preserve, copy the line to the hold space (HS), replace all occurences then append these to the copy and remove the chunk between the two unique markers.

在您想要保存的发生事件之后,放置一个惟一的标记,将该行复制到保存空间(HS),替换所有发生的事件,然后将这些事件附加到副本,并在两个惟一标记之间删除块。

This method should be accomodated by most sed's. If the sed your using does not handle \n's then use a unique string e.g. @@a unique string @@

这个方法应该被大多数sed所适应。如果使用的sed不处理\n,则使用唯一的字符串,例如@@一个唯一的字符串@@。

#2


0  

If your sed was bsd sed, you need check the man page. for the s/../../[flag].

如果您的sed是bsd sed,您需要检查手册页。的s / . . / . . /[标记]。

For Gnu sed:

Gnu sed:

3g means replace from the 3rd occurrence of search pattern, replace all. that is, leave the first and 2nd matches untouched. Example may better explain it:

3g意味着取代第三次出现的搜索模式,取代所有。也就是说,第一场和第二场比赛不要碰。例子可以更好地解释它:

kent$  sed 's/x/y/g' <<< "xxxxxxxxxx"
yyyyyyyyyy

kent$  sed 's/x/y/3' <<< "xxxxxxxxxx"  
xxyxxxxxxx

kent$  sed 's/x/y/3g' <<< "xxxxxxxxxx"
xxyyyyyyyy

#1


1  

This might work for you (GNU sed):

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

sed 's/x/\ny/3;h;s/x/y/g;H;g;s/\n.*\n//' file

Place a unique marker after the occurences you want to preserve, copy the line to the hold space (HS), replace all occurences then append these to the copy and remove the chunk between the two unique markers.

在您想要保存的发生事件之后,放置一个惟一的标记,将该行复制到保存空间(HS),替换所有发生的事件,然后将这些事件附加到副本,并在两个惟一标记之间删除块。

This method should be accomodated by most sed's. If the sed your using does not handle \n's then use a unique string e.g. @@a unique string @@

这个方法应该被大多数sed所适应。如果使用的sed不处理\n,则使用唯一的字符串,例如@@一个唯一的字符串@@。

#2


0  

If your sed was bsd sed, you need check the man page. for the s/../../[flag].

如果您的sed是bsd sed,您需要检查手册页。的s / . . / . . /[标记]。

For Gnu sed:

Gnu sed:

3g means replace from the 3rd occurrence of search pattern, replace all. that is, leave the first and 2nd matches untouched. Example may better explain it:

3g意味着取代第三次出现的搜索模式,取代所有。也就是说,第一场和第二场比赛不要碰。例子可以更好地解释它:

kent$  sed 's/x/y/g' <<< "xxxxxxxxxx"
yyyyyyyyyy

kent$  sed 's/x/y/3' <<< "xxxxxxxxxx"  
xxyxxxxxxx

kent$  sed 's/x/y/3g' <<< "xxxxxxxxxx"
xxyyyyyyyy