1

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?

3
  • 3
    I don't think it exists. For the most part, the various parameter-expansion operators don't stack. Commented May 19, 2021 at 17:53
  • 1
    I concur with chepner. Bash can't really do complex string manipulation compactly. What you wrote is what I would write (maybe reversed so as not to waste time capitalizing letters that are to be discarded). Commented May 19, 2021 at 17:54
  • You can do that in gnu-sed or awk i.e. sed 's/^\(..\).*/\U\1/' <<< "$input" or tr '[[:lower:]]' '[[:upper:]]' <<< "${input:0:2}" Commented May 19, 2021 at 17:55

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.