Lynn
Lynn

Reputation: 19

how to grep a word with only one single capital letter?

The txt file is :

bar
quux
kabe
Ass
sBo
CcdD
FGH

I would like to grep the words with only one capital letter in this example, but when I use "grep [A-Z]", it shows me all words with capital letters.

Could anyone find the "grep" solution here? My expected output is

Ass
sBo

Upvotes: 1

Views: 1369

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627083

You seem to have a text file with each word on its own line.

You may use

grep '^[[:lower:]]*[[:upper:]][[:lower:]]*$' file

See the grep online demo.

The ^ matches the start of string (here, line since grep operates on a line by lin basis by default), then [[:lower:]]* matches 0 or more lowercase letters, then an [[:upper:]] pattern matches any uppercase letter, and then [[:lower:]]* matches 0+ lowercase letters and $ asserts the position at the end of string.

If you need to match a whole line with exactly one uppercase letter you may use

grep '^[^[:upper:]]*[[:upper:]][^[:upper:]]*$' file

The only difference from the pattern above is the [^[:upper:]] bracket expression that matches any char but an uppercase letter. See another grep online demo.

To extract words with a single capital letter inside them you may use word boundaries, as shown in mathguy's answer. With GNU grep, you may also use

grep -o '\b[^[:upper:]]*[[:upper:]][^[:upper:]]*\b' file
grep -o '\b[[:lower:]]*[[:upper:]][[:lower:]]*\b' file

See yet another grep online demo.

Upvotes: 0

user5683823
user5683823

Reputation:

grep '\<[a-z]*[A-Z][a-z]*\>' my.txt

will match lines in the ASCII text file my.txt if they contain at least one word consisting entirely of ASCII letters, exactly one of which is upper case.

Upvotes: 1

Related Questions