Adam Horn Adam Horn - 1 year ago 147
Linux Question

Check Length of string - Linux

I have a file that has a couple thousand lines. I need to make sure that a string is consistently 9 chars long throughout the file and if not, It will kick it back and throw an error everywhere the string is not 9 chars long.


I need the first 9 char to always be 9 chars long and if not, throw an error out.

------ ERRORS ------
Errors found at _, _, _, _, _, _ ...etc.

Answer Source

You can use awk:

awk -F, 'length($1) !== 9 {print "ERROR at line "NR}' file
  • F, sets the field delimiter to ,
  • length($1) !== 9 checks if the first field is 9 chars long
  • print "ERROR at line "NR prints the error message along with the line number NR
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download