sed regex to non-greedy replace?

白昼怎懂夜的黑 提交于 2020-07-06 17:39:59

问题


I am aware of another question that is quite similar, but for some reason I'm still having problems.

I have a GC log that I'm trying to trim out the Tenured section enclosed in [].

63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546: [Tenured: 1416K->1065K(1536K), 0.0492621 secs] 1922K->1065K(2112K), 0.0513331 secs]

I apply s/\[Tenured:.*\]//

And quite expectantly, the result is trimmed greedily through the remainder of the line:

63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546:

So let's try and be non-greedy not match a closing right bracket with s/\[Tenured:[^\]]*\]// but alas no match is made and sed skips over the line, producing the same original output:

63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546: [Tenured: 1416K->1065K(1536K), 0.0492621 secs] 1922K->1065K(2112K), 0.0513331 secs]

How do I non-greedily match and replace that section? Thanks,


回答1:


Almost: s/\[Tenured:[^]]*\]//

The manual says:

To include a literal ']' in the list, make it the first character (following a possible '^').

i.e. No backslash is required in this context.

  • Raz



回答2:


sed -e 's/\[Tenured:[^]]*\]//'

Apparently you shouldn't escape the close square bracket. Wacky!

From man re_format:

A bracket expression is a list of characters enclosed in '[]' ... To include a literal ']' in the list, make it the first character (following a possible `^').




回答3:


Try .*? for the non-greedy variant of .*. (Not sure if it's supported in sed's regex engine or not, but it's worth a try.)

Edit: This previous SO question may be relevant - Non greedy regex matching in sed?




回答4:


This worked:

echo "63.544: [GC 63.544: [DefNew: 575K->63K(576K), 0.0017902 secs]63.546: [Tenured: 1416K->1065K(1536K), 0.0492621 secs] 1922K->1065K(2112K), 0.0513331 secs]" | sed -e s/\\[Tenured:[^\]]*\\]//


来源:https://stackoverflow.com/questions/1685575/sed-regex-to-non-greedy-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!