I have a file with many curly bracketed words, ex. {test1}, {test2} - how would I grep for these words and output a distinct list of them?

output example:


I've tried this which didn't work:

grep -o {.*} file.xml  | sort | uniq


Actually - this seems to have worked:

grep -oP '{.*?}' file.xml | sort | uniq
  • Welcome to Unix & Linux! If you've determined your own solution you can write it up as the answer. – slm Jul 22 '13 at 14:59

There are two problems with your first attempt. {.*} contains special characters which need to be protected from expansion by the shell; put quotes around the pattern. Also, {.*} matches the longest brace-delimited text on the line, so if you have a line containing hello {test1} world {test2} howdy then the output is {test1} world {test2} becaause .* matched test1} world {test2.

The following will output only what is between brackets.

grep -o -e "{[^}]*}" 

My original formulation used "{.*}", but with that the widest bracket found within a line, not the smallest one would be returned...

  • 1
    Good, but why -e? – frostschutz Jul 22 '13 at 15:00
  • Just an old habit. I know, that it's optional as long as there's only one pattern. – soulsource Jul 22 '13 at 15:03
  • @soulsource Can you explain this syntax? {[^}]*} Thanks! – tommy.carstensen Mar 16 '18 at 14:15
  • The [ ] brackets match any character that's written between them. Followed by a * this matches an arbitrary number of characters from the list of characters between the [ ] brackets. The list of characters between the [ ] is in this case ^}, meaning: "any character that's not a }". – soulsource Mar 17 '18 at 15:34
  • Thanks! It was the ^} I didn't understand. Thanks for the explanation! – tommy.carstensen Mar 18 '18 at 2:31

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.