简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM