joe smith
joe smith

Reputation: 23

How do you display all the words that start with 1 uppercase letter using grep in bash?

I tried something like this sed 's/^[ \t]*//' file.txt | grep "^[A-Z].* " but it will show only the lines that start with words starting with an uppercase.

file.txt content:

Something1 something2
word1 Word2
this is lower

The output will be Something1 something2 but I will like for it to also show the second line because also has a word that starts with an uppercase letter.

Upvotes: 2

Views: 1389

Answers (3)

KamilCuk
KamilCuk

Reputation: 141493

How do you display all the words

That's simple:

grep -wo '[A-Z]\w*'

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627083

With GNU grep, you can use

grep '\<[[:upper:]]' file
grep '\b[[:upper:]]' file

NOTE:

  • \< - a leading word boundary (\b is a word boundary)
  • [[:upper:]] - any uppercase letter.

See the online demo:

#!/bin/bash
s='Something1 something2  
word1 Word2  
this  is  lower
папа Петя'
grep '\<[[:upper:]]' <<< "$s"

Output:

Something1 something2  
word1 Word2  
папа Петя

Upvotes: 1

jared_mamrot
jared_mamrot

Reputation: 26690

With GNU grep grep -P "[A-Z]+\w*" file.txt will work. Or, as @Shawn said in the comment below, grep -P '\b[A-Z]' file.txt will also work. If you only want the words, and not the entire line, grep -Po "[A-Z]+\w*" file.txt will give you the individual words.

Upvotes: 1

Related Questions