2

I have a CSV File and I want to have multiple checks to retrieve the data from the CSV file. I have the following conditions which needs to be taken care of and I am trying to use awk in a shell script to fulfill these conditions:

if ( ColD == "TRX" || ColD == "TX" )
{
   if (ColJ == "BTS INT UNAFF" || ColJ == "LOCAL MODE")
   {
      if (ColL !="OPER" && ColL != "") #Second Value shouldn't be blank
      {
         if (ColU != "2000")
         {
             if (ColA != "*_*") # Should not contain _ in the value.
             then
                   print all the resulting filtered columns of this csv file

Here ColA, ColB etc. are the column numbers which i use as $1, $2 and so on.

Now I know simple awk usage of a single if condition is something like this:

awk -F, '{
                if ($23 == "TOP36")
                print $11
            }' $INPUT_PATH/$fileName

and could find the nested if conditions something like this:

awk '
{if ( $6 == 0 && $8 > 0 && $8 <= 9 ) { $6 = "left" } else {
  if ( $8 == 0 && $6 > 0 && $6 <= 15 ) { $6 = "bottom" } else {
    if ( $8 == 9 && $6 > 0 && $6 <= 15 { $6 = "top" } else {
      if ( $6 == 15 && $8 > 0 && $8 <= 9 { $6 = "right" }
      }
    }
  }
} {print}'

But, I think my conditions can be satisfied if I put satisfy one if condition on top and then next under it and so on. How can I do it using awk if statements? Is there a better way to do this?

4

Nested if statements are effectively statement and statement, so if you do not need to do any particular processing as you step through the nesting, then you can just join them all up with &&.

  awk '{ if( ( $4 == "TRX" || $4 == "TX" ) &&
             ( $10 == "BTS INT UNAFF" || $10 == "LOCAL MODE" ) && 
             ( $12 != "OPER" && $12 != "" ) && # Second Value should not be blank
             ( $22 != "2000") &&
             ( !match( $1, "_") ) ) # Should not contain _ in the value.
           { print } 
       }' FS=, file

To define your Field Separator, you can use option -F, instead of parameter FS=, if you prefer – or have it fully contained within the awk code, in the BEGIN{ } pre-file-processing block: BEGIN{ FS="," }

  • And if the only action is print, then you can use just awk FS=, '($4 == "TRX" || $4 == "TX") && … && !match($1, "_")' – Gilles Jul 15 '15 at 23:02
  • Thanks a lot Gary and Gilles for your inputs. I will try this. One more question here, in the last condition, (!match $1, "-") Is this going to ignore all the values in column 1 where value conatins a _ ex: BTS_101, BSC_505 etc? and the hopefully the last print statement prints the entire CSV file data after filtering all the above conditions in the input CSV file? – Ankit Vashistha Jul 16 '15 at 4:36

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.