Bash – Modifying a shell variable with regex (bash)

bashregular expressionshell-scriptstringvariable substitution

I have a shell variable for example. a="big little man". How do I use regex in bash print out the variable with only the middle word capitalized? (big LITTLE man)

I can do it by separating the variable into 3 variables and then expanding them in echo. For eg first=${a%* }, etc. But how do I do it in one single go with one regex?

Is it possible to do it in a single line? Using the capitalize operators (^)

Best Answer

sed

Assuming you're using GNU sed:

$ sed -E 's/(\w+) (\w+) (\w+)/\1 \U\2\E \3/' <<< 'big little man'
big LITTLE man

This command makes use of the GNU specific sequences \U and \E which turn the subsequent characters into upper case and cancel case conversion respectively.

awk

While not operating on regular expressions, awk provides another convenient way to capitalize a single word:

$ awk '{print($1, toupper($2), $3)}' <<< 'big little man'
big LITTLE man

bash

Although Bash on its own does not have regular expression based conversions, you can still achieve partial capitalization by treating your string as an array, e.g.

$ (read -a words; echo "${words[0]} ${words[1]^^} ${words[2]}") <<< 'big little man'
big LITTLE man

Here ^^ converts the second element of our array (i.e. the second word) to upper case. The feature was introduced in Bash 4.

Related Question