Kulpas
Kulpas

Reputation: 394

Bash correct syntax to get first 2 letters of string and make them uppercase

I know I can do what I asked in the title by doing this:

input=abcd
input=${input^^} #makes uppercase
echo ${input:0:2} #gets first two letters

I wanted to know what's the correct syntax for performing both of these operations in a single line?

Upvotes: 1

Views: 199

Answers (2)

tansy
tansy

Reputation: 576

Without declaring an array, using only parameter expansion:

echo $( a=abcd; b=${a:0:2} && echo ${b^^} )

Where:

b=${a:0:2} is taking substring

${b^^} is capitalizing that substring; echo (within command substitution) returnes it

echo (first) prints on the screen

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247172

declare -u input=abcd
echo "${input:0:2}"

See declare in the manual.

This doesn't do precisely what you asked for

get first 2 letters of string and make them uppercase

Instead it makes the value uppercase then gets the first 2 letters.

Upvotes: 7

Related Questions