Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

{test1}
{test2}

I've tried this which didn't work:

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

UPDATE

Actually - this seems to have worked:

grep -oP '{.*?}' file.xml | sort | uniq
share|improve this question
    
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
add comment

1 Answer

up vote 2 down vote accepted

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

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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