1

So I have a text file containing valid and invalid hexadecimal color codes. I want to be able to filter out the invalid codes and print just the valid ones. For a code to be valid it must have a hash symbol, be 6 or 8 characters long after the hash and characters must be a-f or 0-9. My grep command below, is stored in a makefile but it doesn't seem to be reason why my regex isn't working as it is getting rid of the codes that are less than 6 characters but not the ones that are 7 or more than 8 characters long or the codes that have non a-f letters. For testing purposes, I am using -v just to print out the invalid codes as I want to see what codes are matching and what ones aren't.

grep -vE '^#([a-f0-9]{6})|([a-f0-9]{8})$$' colours.txt

Codes:

#b293a6
#ead58f
#31511bxf
#a69d36a2
#067806
#afe6e
#7f0bf7ef
#dd85
#042847421
#1a283af

Output wanted:

#b293a6
#ead58f
#a69d36a2
#067806
#7f0bf7ef

Ouput I'm currently getting:

#afe6e
#dd85

Updated output:

sean@sean-VirtualBox:~/Desktop$ head colours.txt | cat -A
#b293a6^M$
#ead58f^M$
#a69d36a2^M$
#067806^M$
#7f0bf7ef^M$
#f8b366^M$
#042847421^M$
#8946d7^M$
#c927d4^M$
#3e568bff^M$
Casper
  • 29
  • 6

1 Answers1

1

Your alternation pattern is incorrect. ^#([a-f0-9]{6})|([a-f0-9]{8})$$ means ^#[a-f0-9]{6} or [a-f0-9]{8})$ due to misplacement of brackets.

You may use this grep:

grep -ivE '^#[a-f0-9]{6}([a-f0-9]{2})?$' file

#31511bxf
#afe6e
#dd85
#042847421
#1a283af
anubhava
  • 761,203
  • 64
  • 569
  • 643