2016-05-16 6 views
2

grepコマンドを使用して、一致のみを取得しようとしています。grepでのみ一致を取得したい

は、私は、XMLファイルを読んでいると私は唯一の「http://myurl.com/myuri/document」を取得したい

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

タグの場所のURLを取得したいです。 私はこの作られた:

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> 

今、私はこの作られた唯一のURL を取得したい:

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

を私はほとんど勝ちますhaha

chars>とでURLを受け取りました210

どうすれば一致を得ることができますか?例えば (この例のdoesntの仕事)

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

私は、この後にはwgetでVARを使用したいです。 | wget $1

+1

これはgrepとは異なります。 'grep'を使い、結果を' sed'に渡します。 – Mort

答えて

0

私は考えることができる最も簡単な解決策は、sedをされています

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

は、これはURLに貼り付け先のとがった角括弧を取り除くでしょう。

1

ようにあなたは、PCRE正規表現用のGNU grep-Pオプションを使用することができます。

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

またはawkを使用した:Perlの正規表現と

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

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

このエラーメッセージが表示されます。私はMac OS X を使用しています "grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C [num]] \t [-eパターン] [-fファイル] [--binary -files = value] [--color = when] \t [--context [= num]] [--libel] [--line-buffered] \t [--null] [ - パターン] [ファイル...] " –

+0

ok私の更新されたawkコマンドを試してください。 – anubhava

1

はgrepを:

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

または

または、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 を使用しています "grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C [num]] \t [-eパターン] [-fファイル] [--binary -files = value] [--color = when] \t [--context [= num]] [--libel] [--line-buffered] \t [--null] [ - パターン] [ファイル...] " –

+0

@RenatoCassinoあなたは上記の2つからgrepコマンドを試しましたか? – Jahid

+0

@RenatoCassino os xのいくつかのバージョンでは、 'grep -P'の代わりに' pcregrep'コマンドを使う必要があります –

0

は、私はちょうど私が来た実験ので作業anubhavaのバージョンを取得することができませんでした次のように書いてください:–私はGNU版にそれが問題であるかどうか分からないので、私はGNU版を含めました。

私は、探していたものに埋め込まれたXMLタグを扱うことについて少し気になりました(おそらく、場所の使用例の問題ではなく、より一般的な問題としてこれを見ています)。私はまた、結果として得られるテキストの中で<location>..</location>ラッパーを削除しなければならないことも発見しました。

[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>