1

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
oguz ismail
  • 1
  • 16
  • 47
  • 69
Lynn
  • 19
  • 4
  • 1
    Does "word" mean letters only? By default, "word" characters are letters, digit and the underscore. Please clarify - all your test inputs are all-letters, but is that true in your real data? –  Apr 04 '20 at 17:31
  • 1
    `awk -F[A-Z] NF==2`?? – oguz ismail Apr 04 '20 at 17:35
  • @oguzismail - is that a `grep` solution, as the OP requested? –  Apr 04 '20 at 17:37
  • @mathguy nah, that's why it's a comment – oguz ismail Apr 04 '20 at 17:38
  • @mathguy Maybe the OP does not know other tools that could also be useful (not improbable for newcomers). And it's a standard utility, so why not mention it? – Quasímodo Apr 04 '20 at 17:59

2 Answers2

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

0

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563