Using sed to capture the first word with capital letters

Viewed 56

I am interested in retrieving first word in a sentence if it begins with 5 capital letters. For example, if a sentence is SOLAR eclipse, I need SOLAR. If the sentence is SOLA eclipse or solar ECLIPSE or 40 thieves, then nothing.

printf "SOLAR eclipse\nSOLA eclipse\nsolar ECLIPSE\n40 thieves" | sed 's/\(^[A-Z]\{5\}\).*/\1/'
SOLAR
SOLA eclipse
solar ECLIPSE
40 thieves

As we see, the extraction works for the first sentence only. I had expected it would return empty string for the second, third and fourth, but it returns the whole string.

2 Answers

using grep

$printf  "SOLAR eclipse\nSOLA eclipse\nsolar ECLIPSE\n40 thieves" | grep -oE  '^[A-Z]{5}'
SOLAR
$

With awk could you please try following too.

printf "SOLAR eclipse\nSOLA eclipse\nsolar ECLIPSE\n40 thieves" |
awk 'match($0,/^[A-Z]{5}/){print substr($0,RSTART,RLENGTH)}'
Related