Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check field length using awk

Tags:

I have a file of 3 fields:

123710337783,351898014413150,123028040249634 123710337785,352934028758390,123028040109275 

I need to check that the fields meet the following lengths:

Field 1 = 12 Field 2 = 15 or 16 Field 3 = 15 

I get an error when running this:

awk -F, '{if(length($2) == 15 ) || length($2) == 16) && length($1) == 12 && length($3)) == 15) print  }' 

Please assist.

Bernie

like image 398
bernie Avatar asked Jan 10 '11 16:01

bernie


People also ask

How do you find the length of awk?

awk length(string) Function: The length() function calculates the length of a string. Explanation: Length of the string also includes spaces. 3. awk substr(s, p, n) Function: The length() function is used to extract substring function from a string.

How do I count the number of fields in awk?

awk with NF (number of fields) variable. NF is a built-in variable of awk command which is used to count the total number of fields in each line of the input text. Create any text file with multiple lines and multiple words.

What is awk F?

awk -F: '{print $4}' awk - this is the interpreter for the AWK Programming Language. The AWK language is useful for manipulation of data files, text retrieval and processing. -F <value> - tells awk what field separator to use.


2 Answers

All your brackets are mismatched. An 'if' expression must be contained within brackets, i.e.,

if (X == 45) ... if ((X == 45) || (Y == 23)) ... 

you don't have this, and you've got more closing brackets than opening brackets - so the balance is off as well; if we count the brackets (increment for open, decrement for close), we end up with a total of -3 instead of 0, so closing three more brackets than we have open:

            1      2  1       0          1  0     -1          0 -1                0 -1 -2     -3 awk -F, '{if(length($2) == 15 ) || length($2) == 16) && length($1) == 12 && length($3)  ) == 15) print  }' 

So, try this instead which rebalances everything:

awk -F, '{ if (((length($2) == 15 ) || length($2) == 16) && (length($1) == 12 && length($3) == 15)) print }' 
like image 183
Chris J Avatar answered Sep 19 '22 13:09

Chris J


If all you're going to do is print, then put your expression as the default condition:

awk -F, 'length($1)==12 && (length($2)==15 || length($2)==16) && length($3)==15' 

If you're trying to filter out lines in your input file that don't meet this criteria:

awk -F, '     length($1)!=12 || length($2)<15 || length($2)>16 || length($3)!=15) {next}     # do other stuff... ' 
like image 25
glenn jackman Avatar answered Sep 18 '22 13:09

glenn jackman