Skip to content

Instantly share code, notes, and snippets.

@echoes341
Last active March 23, 2023 09:08
Show Gist options
  • Save echoes341/12735fc6318ae4b8097b30536c88bf12 to your computer and use it in GitHub Desktop.
Save echoes341/12735fc6318ae4b8097b30536c88bf12 to your computer and use it in GitHub Desktop.
RGB color notation to HEX and reverse using Awk
#!/bin/awk -f
# Convert awk hex colors to rgb values using awk.
# input line: #000000
# output line: rgb(0,0,0)
{
number = substr($1, 2)
for (i = 1; i <= 3; i++) {
idx = (i - 1)*2 + 1
hexStr = "0x" substr(number, idx, 2)
rgb[i] = strtonum(hexStr)
}
printf("rgb(%d,%d,%d)\n", rgb[1], rgb[2], rgb[3])
}
#!/bin/awk -f
# Convert awk rgb colors to hex values using awk.
# input line: rgb(0,0,0)
# output line: #000000
BEGIN { FS="[(),]" }
/rgb/ {
printf("#%.2x%.2x%.2x\n",$2,$3,$4)
}
@Clockris
Copy link

Hi, thanks for your code. Anyway I found a small bug in hexTorgb.awk:

printf("rgb(%d,%d,%d)\n",rgb[1], rgb[2], rgb[3])

should be

printf( "%d,%d,%d", strtonum( rgb[1] ), strtonum( rgb[2] ), strtonum( rgb[3] ) )

unless awk will not recognise rgb[i] as a number but as a string and it will always print 0,0,0.

@echoes341
Copy link
Author

Hello @Clockris, thanks for telling me! Fixed 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment