2

I have awk script file as below. I need to add another condition in the if statement to check if the string contains atleast one alphabet. How can I add the extra condition to the present if statement?

Required regex condition: [[ "$1" =~ [A-Za-z] ]]

BEGIN { FS = ";"; counter=0}

{ 
 if ((length($1) != 10 && length($1) != 12))
   { 
    counter++
    print counter, $1;
    if ($counter -gt 2){
        print "Invalid input file";
        exit;
    }    
   }
}

I am getting error if I use the same condition which I have posted. How to add the condition?

8

You don't actually show how you add the regex, so I am guessing you are using the same format: =~ [A-Za-z]. That won't work. Each language has its own syntax for regex matching. In awk, the format is $target ~ /$regex/, so $1 ~ /[A-Za-z]/.

BEGIN { FS = ";"; counter=0}

{ 
 if (length($1) != 10 && length($1) != 12 && $1 ~ /[A-Za-z]/)
   { 
    counter++
    print counter, $1;
    if (counter > 2){
        print "Invalid input file";
        exit;
    }    
   }
}

Also, in awk, the $ sign is used to mark fields, not variables. So $counter will be evaluated to the field number of counter. If counter is 2, then $counter will be the value of the second field. And the -gt is also not an awk thing. Just use >.

  • Yes. I was using =~ format. – Laxman Apr 15 at 12:44
  • Why couldnt you move the condition to be the pattern? length($1) != 10 && ... && $1 ~ /[A-Za-z]/ { counter++ ... } seems more « awkish » to me, avoiding some seriously nested braces – D. Ben Knoble Apr 15 at 16:53
  • 1
    @D.BenKnoble why indeed! I just copy/pasted the OP's code and added the regex. I just didn't realize it was that nested. Thanks! – terdon Apr 15 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.