简体   繁体   English

在bash中使用SED打印RegEx匹配

[英]Print RegEx matches using SED in bash

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. 我想要做的是通过Putty从文件中提取“ finalNumber ”属性值。 Rather than having to download a copy and search using notepad++. 而不是必须使用记事本++下载副本和搜索。

I've built up a regular expression that I've tested on an On-line Tool , and tried using it within a sed command to duplicate grep functionality . 我已经构建了一个我在在线工具上测试的正则表达式,并尝试在sed命令中使用它来复制grep功能 The command runs but doesn't return anything. 该命令运行但不返回任何内容。

RegEx: 正则表达式:

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

sed Command (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? 我觉得我很接近(我可能是错的),我是在正确的路线还是有更好的方法来实现输出?

Nothing wrong with good old grep here. 好老grep没问题。

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

Use -E for extended regular expressions, and -o to print only the matching part. 使用-E表示扩展正则表达式, -o表示只打印匹配部分。

Though you already select an answer, here is a way you can do in pure sed: 虽然你已经选择了一个答案,但这里有一种你可以用纯sed做的方法:

sed -n 's/^.*finalNumber="\([[:digit:]]\+\)".*$/\1/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将打印整行,因此您必须替换整行)

这可能适合你(GNU sed):

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

sed does not support look-ahead assertions. sed不支持预见断言。 Perl does, though: 不过Perl确实如此:

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

As I understand, there is no need to use look-aheads here. 据我了解,这里没有必要使用预见。 Try this one 试试这个吧

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM