1

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

sed 's/../\U&:/g;s/:$//' is more direct, but given GNU sed, yes, that's the way.
or sed 's/\(..\)/\U\1:/g;s/:$//'
or perl -pe 's/(..)/\U$1:/g;s/:$//'
2

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.

1 Comment

Or: str=aabbccddeeff a=(); while IFS= read -r -N2 b; do a+=("$b"); done <<< "$str"; IFS=: eval 'printf "%s\n" "${a[*]^^}"'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.