0

I'm new to regex and I'm trying to extract all the unique occurrences of each competition. So it should return FA Cup but only once no matter how many FA Cup games are in the file

<Date="2014-02-15" Competition="FA Cup" Home="West Bromwich Albion">

Based on the accepted solution solution from this question here, I tried this:

grep -o 'Competition=".*\" 'Soccer_Data.xml' | sort --unique

But it is returning everything on the line after Competition=", but I only everything up to the first occurrence of a double quotation mark i.e. "FA Cup". It is also returning the same competition multiple times!

To prevent the multiple returns I tried using .*? as suggested in the solution below but that gave me the opposite problem as it did not return anything!

https://stackoverflow.com/questions/22444/my-regex-is-matching-too-much-how-do-i-make-it-stop

Can someone please tell me what the correct regular expression to use is.

  • 1
    I don't really see a reason to downvote this. Clear question, good research done and shown, correct tagging, ... +1 from me. @Downvoter, Please comment on the reasons. – pLumo Jun 18 '19 at 11:42
1

grep uses Posix Basic regex by default.

.* in basic regex is always a greedy match, meaning it matches anything until the last " in the line.

You can use [^"]* instead to match anything except ".

grep -o 'Competition="[^"]*"' 'Soccer_Data.xml' | sort --unique

Output:

Competition="FA Cup"

Alternatively, use perl compatible regex that provides non-greedy modifier (.*?).
You can use grep -P if your version of grep provides that (and it will, as you have added [ubuntu] tag to your question).

grep -Po 'Competition=".*?"' 'Soccer_Data.xml' | sort --unique

or to receive only FA CUP using e.g. "Keep-out" --> \K:

grep -Po 'Competition="\K[^"]*' 'Soccer_Data.xml' | sort --unique

Output:

FA Cup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.