Use the fileinput
module to create a script that can handle 1 or more files, replacing lines as needed.
Use regular expressions to find your hex RGB value, and take into account that there are two formats; #fff
and #ffffff
. Replace each format:
import fileinput
import sys
import re
_hex_colour = re.compile(r'#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b')
def replace(match):
value = match.group(1)
if len(value) == 3: # short group
value = [str(int(c + c, 16)) for c in value]
else:
value = [str(int(c1 + c2, 16)) for c1, c2 in zip(value[::2], value[1::2])]
return 'rgb({})'.format(', '.join(value))
for line in fileinput.input(inplace=True):
line = _hex_colour.sub(replace, line)
sys.stdout.write(line)
The regular expression looks for a #
followed by either 3 or 6 hexadecimal digits, followed by a word boundary (meaning what follows must not be a character, digit or underscore character); this makes sure we don't accidentally match on a longer hexadecimal value somewhere.
The #hhh
(3 digit) patterns are converted by doubling each hex digit; #abc
is equivalent to #aabbcc
. The hex digits are converted to integers, then to strings for easier formatting, then put into a rgb()
string and returned for replacement.
The fileinput
module will take filenames from the command line; if you save this as a Python script, then:
python scriptname.py filename1 filename2
will convert both files. Without a filename stdin
is used.