Linux 在 bash 中使用 SED 打印 RegEx 匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14479535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:46:32  来源:igfitidea点击:

Print RegEx matches using SED in bash

regexlinuxbashsed

提问by Matthew Warman

I have an XML file, the file is made up of one line.

我有一个 XML 文件,该文件由一行组成。

What I am trying to do is extract the "finalNumber" attribute value from the file via Putty. Rather than having to download a copy and search using notepad++.

我想要做的是finalNumber通过 Putty 从文件中提取“ ”属性值。而不必下载副本并使用记事本++进行搜索。

I've built up a regular expression that I've tested on an On-line Tool, and tried using it within a sedcommand to duplicate grep functionality. The command runs but doesn't return anything.

我已经建立了一个正则表达式,我已经在一个在线工具上测试过,并尝试在sed命令中使用它来复制 grep 功能。该命令运行但不返回任何内容。

RegEx:

正则表达式:

(?<=finalNumber=")(.*?)(?=")

sedCommand (returns nothing, expected 28, see file extract):

sed命令(不返回任何内容,预期为 28,请参阅文件摘录):

sed -n '/(?<=finalNumber=")(.*?)(?=")/p' file.xml

File Extract:

文件提取:

...argo:finalizedDate="2012-02-09T00:00:00.000Z" argo:finalNumber="28" argo:revenueMonth=""...

I feel like I am close (i could be wrong), am I on the right lines or is there better way to achieve the output?

我觉得我很接近(我可能是错的),我是在正确的路线上还是有更好的方法来实现输出?

采纳答案by Perleone

Nothing wrong with good old grep here.

这里的老式 grep 没什么问题。

grep -E -o 'finalNumber="[0-9]+"' file.xml | grep -E -o '[0-9]+'

Use -Efor extended regular expressions, and -oto print only the matching part.

使用-E的扩展正则表达式,并-o只打印匹配的部分。

回答by choroba

seddoes not support look-ahead assertions. Perl does, though:

sed不支持前瞻断言。但是,Perl 确实如此:

perl -ne 'print  if /(?<=finalNumber=")(.*?)(?=")/'

回答by Alexey Shumkin

As I understand, there is no need to use look-aheads here. Try this one

据我了解,这里没有必要使用前瞻。试试这个

sed -n '/finalNumber="[[:digit:]]\+"/p'

回答by potong

This might work for you (GNU sed):

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

sed -r 's/.*finalNumber="([^"]*)".*//' file

回答by texasbruce

Though you already select an answer, here is a way you can do in pure sed:

尽管您已经选择了一个答案,但您可以在纯 sed 中执行以下操作:

sed -n 's/^.*finalNumber="\([[:digit:]]\+\)".*$//p' <test

Output:

输出:

28

This replaces the entire line by the match number and print (because p will print the entire line so you have to replace the entire line)

这将用匹配号替换整行并打印(因为 p 将打印整行,因此您必须替换整行)