0

I want a regex using the grep command which only prints out the hexadecimal-notated strings.

This is my command:

grep "0x[A-Fa-f0-9]{1,6}" test.txt

test.txt:

0x2a
0xF
0x1111
0x0ZZZ
0x4dz5

Expected output:

0x2a
0xF
0x1111

Output: Empty

How to do this? Thanks

  • Do you require the hex string to be by itself on a line? Or separated from surrounding characters by ... a space? Non-hex char? – Jeff Schaller Oct 12 '17 at 17:43
  • @JeffSchaller All strings will be on a separate line anyway, so nothing special for that needed. – O'Niel Oct 12 '17 at 17:44
2

The {n,m} syntax is part of the Extended Regular Expression set, which means that you need to enable that in grep with the -E flag. To require that the full line matches the hex representation, add the -x flag (or use the ^ and $ anchors):

grep -Ex '0x[A-Fa-f0-9]{1,6}'

or

grep -E '^0x[A-Fa-f0-9]{1,6}$'

I also changed the surrounding quotes from double- to single-, to prevent unintended expansion of the $ character.

More regex reading on Stack Exchange:

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.