Shell – Check if content of file has length X and contains only specific characters

shellstring

Let's say, I have files that contain only one docker id:

myid.id:

28fe2baadbe8da32ed0b99c69b11c01b2d141bc5b732b81e0960086de52fc891

I want to check if the content of my.id is exactly 64 characters long and contains only characters in the range [0-9] and [a-z] (maybe [a-f]).

  • How can I do that?
  • If the file contains a newline 0x0a, how can I include/exclude it in this check?

Best Answer

Try:

$ echo 28fe2baadbe8da32ed0b99c69b11c01b2d141bc5b732b81e0960086de52fc891 | 
awk '{sub(/\r/,"")} length == 64 && /^[[:xdigit:]]+$/'
28fe2baadbe8da32ed0b99c69b11c01b2d141bc5b732b81e0960086de52fc891

or use perl instead.

Include newline:

perl -ne 'print if length == 64 and /^[[:xdigit:]]+$/'

Exclude newline:

perl -nle 'print if length == 64 and /^[[:xdigit:]]+$/'
Related Question