Let's say we have the following string:
aabbccddeeff
How can I transform this string to:
AA:BB:CC:DD:EE:FF
Can it be done with regex or something more easier?
Use & at the replacement part to refer all the matched characters.
$ echo 'aabbccddeeff' | sed 's/.*/\U&/;s/\(..\)/\1:/g;s/:$//'
AA:BB:CC:DD:EE:FF
sed 's/../\U&:/g;s/:$//' is more direct, but given GNU sed, yes, that's the way.sed 's/\(..\)/\U\1:/g;s/:$//'perl -pe 's/(..)/\U$1:/g;s/:$//'A Bash-only solution, as a one-liner:
str=${str^^*} ; for (( i=0 ; i<${#str} ; i+=2 )) ; do [[ i -ne 0 ]] && echo -n ":" ; echo -n ${str:i:2} ; done ; echo
and expanded:
# convert string to uppercase:
str=${str^^*}
# loop through each pair of characters:
for (( i=0 ; i<${#str} ; i+=2 ))
do
# if it is not the first pair, add a leading colon:
[[ i -ne 0 ]] && echo -n ":"
# print this part of the string:
echo -n ${str:i:2}
done
# add a newline:
echo
Please read this as a demonstration of what Bash can do. Code like this is not portable and probably a little less maintainable than other solutions. It offers better performance, but this will not often be an issue.
str=aabbccddeeff a=(); while IFS= read -r -N2 b; do a+=("$b"); done <<< "$str"; IFS=: eval 'printf "%s\n" "${a[*]^^}"'.