tags:

views:

62

answers:

2

Nice and (hopefully) easy. I am trying to work out how to grab the variable #XXX from a text file (css file) containing strings like

hr { margin: 18px 0 17px; border-color: #ccc; }

h1 a:hover, h2 a:hover, h3 a:hover { color: #001100; }

Which I would like to return as

ccc

001100

The plan then is to throw this through sort and uniq and the end up with a defining colourscheme for the page.

Basically, I can't work out how to go from matching /color:#...[...]/ to just printing out the wildcarded sections.

+1  A: 
sed -n '/color/ s/.*color: *#\([^;]\+\);.*/\1/p' css_file

You could add some more optional whitespace:

sed -n '/color/ s/.*color:[[:space:]]*#[[:space:]]*\([[:xdigit:]]\+\)[[:space:]]*;.*/\1/p'
Dennis Williamson
Almost perfect, the second [[:space:]] needed to be made optional, and clause extended to restrict to [[:xdigit:]], but thanks!Final answer I use is sed -n '/color/ s/.*color:[[:space:]]*#[[:space:]]*\([[:xdigit:]]\+\)[[:space:]]*;.*/\1/p'
Andrew Bolster
I made the changes you pointed out. Thanks.
Dennis Williamson
A: 

here's 2 possible (and easier to read) ways with awk

awk -F"#" '/color/{sub(";.*","",$NF);print $NF}' file

awk -vFS="#|; *}" '/color/{print $2}' file
ghostdog74
possible and easier,but more fragile; I quite like the first one.in the second case, your solution correctly operates for the example case, but"p { margin: 18px 0 17px; background-color: #ccc; color:#123}"would be missed, as would "p { margin: 18px 0 17px; background-color: #ccc; color:#123} h1 a:hover, h2 a:hover, h3 a:hover { color: #001100; }"Cheers anyway!
Andrew Bolster