Bill Herrman
Bill Herrman

Reputation: 65

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.

xxxxxxxxx,xxx

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

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

Upvotes: 1

Views: 1926

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

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

Upvotes: 2

bishop
bishop

Reputation: 39364

You can use grep to list non-matches. Using GNU grep:

grep -vEn '^[^,]{9},' file

This lists all lines (prefixed with line number) that don't start with exactly 9 non-commas followed by a comma. Example:

$ cat file
1234567890,foo
123456789,bar
12345678,baz

$ grep -vEn '^[^,]{9},' file
1:1234567890,foo
3:12345678,baz

Upvotes: 2

Related Questions