2016-05-16 366 views
2

我想使用grep命令只获得匹配。想要得到匹配grep

我读一个XML文件,我想在网址标签位置

<?xml> 
<!-- ..... --> 
<location>http://myurl.com/myuri/document</location> 

我只想得到“http://myurl.com/myuri/document”。 我做了这个:

curl http://mywebsite.com/file.xml | grep "\<location\>" 

我收到完整标签:

<location>http://myurl.com/myuri/document</location> 
<location>http://myurl.com/myuri/document2</location> 
<location>http://myurl.com/myuri/document3</location> 

现在,我想只有 我做了这个网址:

curl http://mywebsite.com/file.xml | grep "\<location\>" | grep -oh ">.*<" 

和我差不多赢哈哈

我收到了带有字符的网址>和<

>http://myurl.com/myuri/document< 

我怎样才能得到匹配? 例如(这个例子不工作)

curl http://mywebsite.com/file.xml | grep "\<location\>" | grep -oh ">(.*)<" 
http://myurl.com/myuri/document 

我想使用var中的wget在此之后。像| wget $1

+1

这不仅仅是grep的用处。使用'grep',然后将结果传递给'sed'。 – Mort

回答

0

我能想到的是sed最简单的办法:

... | sed -e 's/^>//' -e 's/<$//' 

这将摆脱停留在URL中的尖括号。

1

您可以在GNU grep使用-P选项PCRE正则表达式:

curl http://mywebsite.com/file.xml | grep -oP '<location>\K[^<]+' 

或者用awk:

curl http://mywebsite.com/file.xml | awk -F '</?location>' '/<location>/{print $2}' 

http://myurl.com/myuri/document 
+0

我收到此错误消息。我使用的是mac os X “usage:grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C [num]] \t [-e pattern] [-f file] [--binary -files = value] [--color = when] \t [--context [= num]] [--directories = action] [--label] [--line-buffered] \t [--null] [模式] [文件...]“ –

+0

好的尝试我更新的awk命令。 – anubhava

1

的grep用Perl的正则表达式:

grep -oP '(?<=<location>)[^<]+(?=</location>)' 

或者

grep -o '[^<>]\+</location>' |grep -o '^[^<>]\+' 

或者与SED:

sed -n 's#<location>\([^<]\+\)</location>#\1#p' 

如果你想下载所有这些URL,然后:

curl http://mywebsite.com/file.xml | 
grep -o '[^<>]\+</location>' |grep -o '^[^<>]\+' | 
wget -ci - 
+0

我收到此错误讯息。我使用的是mac os X “usage:grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C [num]] \t [-e pattern] [-f file] [--binary -files = value] [--color = when] \t [--context [= num]] [--directories = action] [--label] [--line-buffered] \t [--null] [模式] [文件...]“ –

+0

@RenatoCassino你从上面两个尝试哪个grep命令? – Jahid

+0

@RenatoCassino在os x的某些版本中,您需要使用命令'pcregrep'来代替'grep -P' –

0

我是不是能够得到anubhava版的工作,所以只是尝试我来了请注意以下–请注意,我已经包含了GNU版本,因为我不确定它是否存在问题。

我在处理嵌入的XML标签时,有点担心被搜索的内容(可能不是您的示例使用位置的问题,而是将其看作更普遍的问题)。我还发现,我必须在结果文本中删除<location>..</location>包装器,因此需要删除两个sed命令。

[email protected]:~/ateb/myx$ grep --version 
grep (GNU grep) 2.24 

[email protected]:~/ateb/myx$ cat tmp.tmp 
<location><test>123</test></location> 

[email protected]:~/ateb/myx$ cat tmp.tmp | grep -o '<location>.*</location>' | sed 's;<location>;;' | sed 's;</location>;;' 
<test>123</test>