How to capitalize and replace characters in shell script in one echo

Viewed 427

I am trying to find a way to capitalize and replace dashes of a string in one echo. I do not have the ability to use multiple lines for reassigning the string value.

For example: string='test-e2e-uber' needs to echo $string as TEST_E2E_UBER

I currently can do one or the other by utilizing

${string^^} for capitalization

${string//-/_} for replacement

However, when I try to combine them it does not appear to work (bad substitution error). Is there a correct syntax to achieve this?

echo ${string^^//-/_}

3 Answers

This does not answer directly your question, but still following script achieves what you wanted :

declare -u string='test-e2e-uber'
echo ${string//-/_}

Why do you dislike it so much to have two successive assignment statements? If you really hate it, you will have to revert to some external program to do the task for you, such as

string=$(tr  a-z- A-Z_ <<<$string)

but I would consider it a waste of resources to create a child process for such a simple operation.

  1. You can do that directly with the 'tr' command, in just one 'echo'
echo "$string" | tr "-" "_" | tr "[:lower:]" "[:upper:]"
TEST_E2E_UBER

I don't think 'tr' allows to do the conversion of 2 objects in one command only, so I used pipe for output redirection

  1. or you could do something similar with 'awk'
echo "$string" | awk '{gsub("-","_",$0)} {print toupper($0)}'
TEST_E2E_UBER

in this case, I'm replacing with 'gsub' the hyphen, then i'm printing the whole record to uppercase

Related