我需要提取一部分可能在每行中出现1到n次的字符串。
例如,这将反映出我的需求:
This [dbo].[something] is a text containing [dbo].[something_else], then okay?
And then, [dbo].[something] may appear just once.
But why, nothing prevents [dbo].[something] from appearing twice as [dbo].[something] here.
And then can be three times, as [dbo].[something] is [dbo].[anything] but [dbo].[elsewhere] here.
[dbo].[otherthing] depicts another scenario with just one and pattern heading line
Or, also [dbo].[ultra] with an arbitrary amount of [dbo].[references] but ending with [dbo].[pattern]
您可能已经注意到,模式为\[dbo\]\.\[[^]]+\]
。例如,从上面的文本中,我希望得到以下结果:
something something_else
something
something something
something anything elsewhere
otherthing
ultra references pattern
然后,我可以将所有内容都内联(或追加到bash数组中)并过滤重复项,这不应该成为问题。我只是很难弄清楚如何在一次扫描中执行此过滤器。
我在这里所得到的结果只是提取了最后一个匹配项(很明显为什么您习惯使用sed的“贪婪”方法进行模式匹配):
cat dborefs.txt | sed -E "s/(.*\[dbo\]\.\[([^]]+)\].*)*/\2/g"
something_else
something
something
elsewhere
otherthing
pattern
我可以提取,然后替换模式,使其不再匹配,然后再次提取,直到不再匹配,但这听起来太麻烦了,考虑了所有bash开销;最好能够在一次调用中提取所有内容sed
。我认为这应该是可能的,只是无法轻易弄清楚如何做到。认为这对其他人可能有用,我觉得在这里分享此事可能会为社区带来丰硕的成果。
就目前而言,我希望(希望)比反复调用sed好得多的是用占位符“链接”替换,希望这些占位符不会出现在文件中。
cat dborefs.txt | sed -E "
s/\[dbo\]\.\[([^]]+)\]/_-\1-_/g;
s/(^|-_)([^_]+|_[^-])*(\$|_-)/ /g;
s/(^ +| +\$)//g"
换句话说:
[dbo].[<extract>]
并替换为_-<extract>-_
;_-
,之前-_
和之间以及_-
最后-_
一个之后的任何文本替换为单个空格字符;这样可以达到预期的结果,我也许可以将其全部加入一个数组中,然后使用sort
进行过滤以查找唯一的条目。但是我仍然认为,没有链式sed
命令应该有更好的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句