Sed / Awk – Find string exactly n characters long

awkgrepsed

Looking through the man pages for sed, awk and grep, I'm unable to find a way to search for a string that is exactly n characters long.

Given the following text file, I want to extract just 6982a9948422

ID                  IMAGE               COMMAND                
CREATED             STATUS              PORTS
6982a9948422        ubuntu:12.04        apt-get install ping   
1 minute ago        Exit 0

The value will always be in the first column and is always 12 alphanumeric characters.

Here is what I am trying so far.

 cat /tmp/test | awk {'print $1'} | sed 's/.*\([0-9],[A-Z],[a-z]\{12\}\).*//g'

What would be a way to extract just 6982a9948422 from the text above ?

Best Answer

awk 'length($1) == 12 { print $1 }' file

The program is pretty self documenting and avoids the regex hammer.

awk -v f=1 '$f ~ /^[[:alnum:]]{12}$/ { print $f }' file

Or swing away with the above if you only want to consider first fields (fields being delimited by blanks) that consist only of alphanumeric characters.

With awk implementations that don't support the {x,y} interval regular expressions, you can change it to:

awk -v f=1 'length($f) == 12 && $f !~ /[^[:alnum:]]/ { print $f }' file
Related Question