OK so I'm extremely new to bash shell scripting and I've been pretty successful up until this point. I'm using BASH to fix a problem...

I want to turn a basic domain name: Buddies.forlife.com into |07|Buddies|07|forlife|03|com

Basically, I need it to count the letters and convert it to hex. To be clear, Not convert the domain name to hex, but the letter count to hex. I'm having a hard time replacing the period "."

I hope you understand what I'm trying to achieve...

Thanks for the help in advance!

  • So you solved the counting, and want us to tell you how to replace the periods? – a CVn Jun 3 '16 at 14:11
  • Well Both if possible. I hand jammed those numbers in to demonstrate the outcome I'm looking for. – DrManhattan Jun 3 '16 at 15:11
  • Oh and the count is in hex so after the numbers... 0a, 0b.... u get the rest. – DrManhattan Jun 3 '16 at 15:14

Here is a straightforward way to do this using awk

echo "Buddies.forlife.com" | awk -F '.' '{ printf( "|0x%x|%s|0x%x|%s|0x%x|%s\n", length($1),$1, length($2),$2, length ($3), $3 )}'

The awk command is setting the field separator -F '.' to a period, so each segment is considered it's own field.

We can then refer to those fields by $1, $2 and $3, use the builtin function length to get the character count for each field, and use a printf to print out the results (%x for hex numbers, %s for the original strings, and output field separation using the '|' symbol, in the format you had specified.

The 0xprefix is typically used to indicate hex numbers, but can be changed to something else (or nothing) as needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.