1

I have code that parses through a csv file and then checks each field against a regex. however there are a few fields that need to be mandatory if another field has data in it, so I essentially need a conditional block to control the flow of data . so for example of sample file see below

 "S","HEY","J","B","0",""

so what I need is a way to say

if $1 == "S"
USE THIS regex ($3~/^("[A-Z0-9]{1}")$/) {print "3RDfield invalid-HEADER-FILE";}
else 
USE THIS REGEX ($3~/^("")$/) {print "3RDfield invalid-HEADER-FILE";}

I have tried using inline version

$1== "S" && ($3~/^"[A-Z0-9]{1}"$/) {print "3RD field invalid-HEADER-      FILE";}  
$1 != "S" && ($3~/^("")$/) {print "3RDfield invalid-HEADER-FILE";}
  • Why not $1 != "S" && ($5~/^("")$/) for that second block? That's what you initially described. – Kusalananda Mar 11 at 10:24
  • That should be $1=="\"S\"" && .., $44!="\"B\"" && .., right? (otherwise it will match S,... (an unquoted S as $1). – mosvy Mar 11 at 10:30
  • @Kusalananda apologies I copied the wrong segment of code see post for correct version – jordanb111 Mar 11 at 10:35
1
 {
   if ($1 == "\"S\"")
     regex = "^\"[[:upper:][:digit:]]\"$"
   else
     regex = "^\"\"$"
 }
 $5 ~ regex {print "error"}

Or using the ternary operator:

 $5 ~ ($1 == "\"S\"" ? "^\"[[:upper:][:digit:]]\"$" : "^\"\"$") {
   print "error"
 }

Note that [A-Z], [0-9] could (and in practice sometimes do) match just about anything in locales other than C, while [[:digit:]] matches [0123456789] and [[:upper:]] uppercase letters (all the ones in the locale, not necessarily limited to latin ones without diacritics).

{1} is superfluous.

  • unfortunately due to the system this will be implemented on it doesn't have posix support so [[:upper:]] and the like wont work on the system hence the older a-z method – jordanb111 Mar 11 at 10:37
  • and yes you are correct about {1} I have now removed it – jordanb111 Mar 11 at 10:39
  • @jordanb111, OK. If it doesn't support POSIX character classes, chances are it won't support {1} either (superfluous anyway). If [A-Z] matches other characters than ABCDEFGHIJKLMNOPQRSTUVWXYZ, you can always replace it with [ABCDEFGHIJKLMNOPQRSTUVWXYZ] or fix the locale to C. – Stéphane Chazelas Mar 11 at 10:39
  • in my testing it hasn't matched any other characters but I will continue and see if it matches anything else – jordanb111 Mar 11 at 10:46
  • @jordanb111, in a locale using the UTF-8 charset, you can do perl -XCO -le 'print chr($_) for 0x1..0xd7ff,0xe000..0x10ffff' | awk '/^[A-Z]$/' to find the single-character collating elements that [A-Z] matches (it may also match multi-character collating elements like Hungarian Dzs). For /usr/xpg4/bin/awk on Solaris, I get 1205 characters, including b-z – Stéphane Chazelas Mar 11 at 10:59

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.